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

Introduction

jlens evaluates JSONata expressions against JSON documents. You can use it to filter, query and transform payloads, and to express business rules whose outcome must be explained.

It ships in five forms that share a single engine:

DistributionPackageUse it for
Rust cratejlens-core (+ jlens-schema)Embedding the engine in Rust services
Command linejlens binaryScripts, pipelines, NDJSON filtering, debugging expressions
WebAssemblyjlens-wasm (npm package, ES module)Browsers: evaluation, editors with autocomplete, audit viewers
Pythonjlens (PyPI package)Data pipelines and rules in Python: evaluation, host functions, audits
Javaio.github.thkprado:jlens (Maven Central)Services and rules on the JVM, virtual threads included: evaluation, host functions, audits

To try it without installing anything, open the web editor: it runs jlens in your browser, with completion, diagnostics, and the explanation and audit tree of every result.

What sets jlens apart from other JSONata implementations:

  • Explainable evaluation. jlens can record an audit tree of how an expression reached its result: which comparisons passed or failed, which items a filter rejected, and which values were bound. You can attach business labels through ordinary JSONata comments (annotations), so the expression stays valid in any other JSONata implementation.
  • Schema-driven assistance. jlens infers structural metadata from sample documents. It then uses that metadata to offer completion, diagnostics and hover information for expressions being written, in the browser and in editors (language server).
  • Conformance first. The engine is checked against the official JSONata test suite (2.3.0) on every change, and against jsonata-js itself with generated expressions every week; see Conformance testing.

Status: jlens 0.37 implements all of JSONata 2.3 (1,970 of the 1,972 test cases of jsonata-js 2.3.0, template strings included; the other two are documented differences), host functions, evaluation audits, schema-driven editor support with a language server, a command line for scripts and agents that checks and tests expressions, and the browser package. See the roadmap.

Installation

jlens comes in five forms that share one engine. Install the ones you need.

Command line

Each GitHub release has the jlens binary for Linux (x86-64 and ARM64, static), macOS (Intel and Apple silicon) and Windows (x86-64), with a SHA256SUMS file. Download the archive for your platform and put jlens on your PATH, or let cargo binstall do it:

cargo binstall jlens-cli

From 0.6.0 on, each archive has a build attestation: a signed statement that the release workflow of this repository built it, from which commit. Check one with the GitHub CLI:

gh attestation verify jlens-0.37.0-x86_64-unknown-linux-musl.tar.gz --repo thkprado/jlens

Elsewhere, build it from source with Rust 1.88 or later and a C compiler:

cargo install jlens-cli                          # from crates.io
cargo install --git https://github.com/thkprado/jlens jlens-cli
cargo install --path crates/jlens-cli            # from a checkout
$ jlens --version
jlens 0.37.0

On macOS and Linux, Homebrew installs the same binary from the tap thkprado/homebrew-jlens (from 0.14.0 on), and brew upgrade follows the releases:

brew install thkprado/jlens/jlens

On Windows, Scoop installs it from the bucket thkprado/scoop-jlens (from 0.14.0 on), and scoop update jlens follows the releases:

scoop bucket add jlens https://github.com/thkprado/scoop-jlens
scoop install jlens/jlens

In a JavaScript project, the same binary comes from npm, in the package jlens-cli (from 0.21.1 on):

npx jlens-cli --version              # run it without installing
npm install --save-dev jlens-cli     # or add it to the project; npm scripts then run `jlens`

jlens-cli runs the release binary for your platform, which npm installs from one of its optional dependencies, jlens-cli-<os>-<cpu>, with no install script. Each run starts Node.js first, which adds some tens of milliseconds. An install with --omit=optional leaves the binary out, and so does a platform without a release binary (Windows on ARM64, for one): jlens then says which package it looked for and exits with code 2.

With Docker or Podman, the container image ghcr.io/thkprado/jlens (from 0.14.0 on) runs the static Linux binary, for linux/amd64 and linux/arm64, with nothing else in the image. It is tagged with each version (0.37.0), each minor version (0.37) and latest. Give it -i to read standard input, or mount the current directory on /work to read files:

echo '{"a": [1, 2]}' | docker run --rm -i ghcr.io/thkprado/jlens eval '$sum(a)'
docker run --rm -v "$PWD:/work" ghcr.io/thkprado/jlens eval -f rule.jsonata -i order.json

The image runs as an unprivileged user (UID 65532): add --user "$(id -u):$(id -g)" for files that only you can read. It has a build attestation too:

gh attestation verify oci://ghcr.io/thkprado/jlens:0.37.0 --repo thkprado/jlens

Install the command through one channel. With more than one, the first jlens on the PATH runs, whatever its version; inside npm scripts and npx, the project’s own jlens-cli comes first. To see which one runs:

jlens --version
which -a jlens       # Linux and macOS: every jlens on the PATH, the one that runs first
where.exe jlens      # Windows

The CLI guide describes every command.

Rust crates

[dependencies]
jlens-core = "0.37"    # the language: parsing, evaluation, functions, auditing
jlens-schema = "0.37"  # optional: schema inference and the language service
serde_json = "1"

jlens-core depends on serde_json, indexmap, jlens-regress (a fork of regress) and a few small crates. The optional tracing feature adds tracing spans for evaluations; see the audit guide. The crate guide shows how to use the API.

Browser and JavaScript

The WebAssembly package is the npm package jlens-wasm, an ES module:

npm install jlens-wasm

From 0.6.0 on, the package is published with provenance: its page on npmjs.com links it to the commit and the workflow run that built it, and npm audit signatures checks it in a project that depends on it.

To build it from a checkout instead, you need:

  • the wasm32-unknown-unknown Rust target;
  • the wasm-bindgen CLI, at the version in Cargo.lock.
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version <version in Cargo.lock> --locked
cargo xtask wasm          # writes crates/jlens-wasm/pkg

The WebAssembly guide covers loading the module in browsers, bundlers and Node.js.

Python

The Python package is jlens on PyPI, from 0.17.0 on, for CPython 3.10 and later:

pip install jlens

Each release has wheels for Linux (x86-64 and ARM64, glibc 2.28 or later and musl), macOS (Intel and Apple silicon) and Windows (x86-64): one for Python with the GIL, and one for free-threaded Python 3.15 and later. Elsewhere, and for free-threaded Python 3.14, pip builds the source distribution, which needs Rust 1.88 or later. The packages are published from the release workflow with attestations, which link each file to the commit and the workflow run that built it.

The Python guide shows how to use it, and how to build it from a checkout.

Java

The Java package is io.github.thkprado:jlens on Maven Central, from 0.25.0 on, for Java 25 and later. With Maven:

<dependency>
  <groupId>io.github.thkprado</groupId>
  <artifactId>jlens</artifactId>
  <version>0.37.0</version>
</dependency>

With Gradle:

implementation("io.github.thkprado:jlens:0.37.0")

Its one JAR carries the native libraries of Linux (x86-64 and ARM64, glibc 2.28 or later and musl), macOS (Intel and Apple silicon) and Windows (x86-64), and loads the one of the platform it runs on. The package calls native code: start the JVM with --enable-native-access=io.github.thkprado.jlens on the module path, or --enable-native-access=ALL-UNNAMED on the class path, or Java prints a warning at first use. The files on Maven Central are signed with the release key D007C3464271F80C1C1DF11BF1B365D7F599090B, on keyserver.ubuntu.com.

The Java guide shows how to use it, and how to build it from a checkout.

This book

The documentation is an mdBook:

cargo install mdbook
mdbook serve docs        # http://localhost:3000
cargo xtask doc-check    # runs the examples and checks the links

First steps

This tour uses the jlens command line and the files in fixtures/. They describe a store order: a customer and a list of items, each with a type, a color, a unit price, a quantity and a tax. Every command runs from the repository root.

{
  "number": "SO-12345",
  "customer": { "login": "alice.walker99", "name": "Acme Stores" },
  "items": [
    { "code": "1", "color": "blue",  "type": "apparel",    "unitPrice": 10000.0, "quantity": 2, "tax": 1500.0 },
    { "code": "2", "color": "black", "type": "electronic", "unitPrice": 25000.0, "quantity": 1, "tax": 4000.0 },
    { "code": "3", "color": "white", "type": "electronic", "unitPrice": 12000.0, "quantity": 1, "tax": 3000.0 }
  ]
}

Query

A path selects values. Predicates in square brackets filter them:

$ jlens eval -i fixtures/online-store-order.json 'customer.name'
"Acme Stores"

$ jlens eval -i fixtures/online-store-order.json -c 'items[type = "electronic"].code'
["2","3"]

$ jlens eval -i fixtures/online-store-order.json '$sum(items.(unitPrice * quantity))'
57000

The language reference explains paths, operators and functions.

Write a rule

fixtures/shipping-rule.jsonata is a business rule. Variables hold intermediate totals, then a condition chooses the outcome:

(
  $total       := $sum(items.(unitPrice * quantity));
  $electronics := $sum(items[type = 'electronic'].(unitPrice * quantity));

  $approved := (
    /** @label "Authorized customer" @message "The customer login must be on the approved partners list." */
    customer.login in ["alice.walker99", "bob.harrison42"]
    and
    /** @label "Minimum order grand total" @message "The order grand total must exceed 50,000.00." */
    $total > 50000
    and
    /** @label "Electronics group" */
    ($electronics > $total * 0.30 + 1000)
  );

  $approved
    ? { "action": "FREE_SHIPPING", "code": "OK_200" }
    : { "action": "REGULAR_FEE", "code": "SHIP_FEE_402", "delivery": "SLOW" }
)

(The fixture has a few more checks; this is the gist.)

$ jlens eval -f fixtures/shipping-rule.jsonata -i fixtures/online-store-order.json
{
  "action": "FREE_SHIPPING",
  "code": "OK_200"
}

Explain the result

The /** @label ... */ comments are annotations. They are ordinary comments to other JSONata implementations, but jlens uses them to explain results:

$ jlens eval -f fixtures/shipping-rule.jsonata -i fixtures/online-store-order.json --explain
result: {"action":"FREE_SHIPPING","code":"OK_200"}
• $total := $sum(items.(unitPrice * quantity)) = 57000
• $electronics := $sum(items[type = 'electronic'].(unitPrice * quantity)) = 37000
  • [type = 'electronic']: 2 of 3 items passed; rejected: {"code":"1","color":"blue",...}
✔ $approved := ( customer.login in [...] and ... ) = true
  ✔ Authorized customer — customer.login in [...] → true ("alice.walker99" in [...])
  ✔ Minimum order grand total — $total > 50000 → true (57000 > 50000)
  ✔ Electronics group — ... → true
      ✔ $electronics > $total * 0.30 + 1000 → true (37000 > 18100)
• $approved ? { ... } : { ... } → {"action":"FREE_SHIPPING","code":"OK_200"} [then]

(Output shortened.) --audit json prints the full audit tree for programs to read. The audit guide explains audits, levels and annotations.

Get help while writing

jlens can infer a schema from sample documents. Using it, jlens check reports fields that do not exist, and the language service completes field names:

$ jlens schema infer fixtures/online-store-order.json -o order.schema.json
inferred from 1 sample(s): order.schema.json

$ jlens check --schema order.schema.json 'items[type = "electronic"].unitprice'
warning[W0201]: Field "unitprice" is not in the schema; did you mean `unitPrice`?
 --> <expr>:1:28
  |
1 | items[type = "electronic"].unitprice
  |                            ^^^^^^^^^

$ jlens schema complete --schema order.schema.json "items[type = 'electronic']."
code                     field     string
color                    field     string
type                     field     string
unitPrice                field     number
quantity                 field     integer
tax                      field     number

The same service drives editors in the browser; try the examples/web-editor demo (WebAssembly guide).

Next

Coming from jsonata-js

jlens targets the behaviour of jsonata-js 2.3.0. An expression that works there gives the same result here: jlens is checked against the official test suite on every change, and against jsonata-js itself with generated expressions every week (Conformance testing). What changes is the API around the expression.

This page is for a JavaScript application that calls jsonata-js today. Compatibility with jsonata-js lists every difference in the language, with its reason.

The same evaluation in both

With jsonata-js:

import jsonata from "jsonata";

const expression = jsonata("$double($sum(items[type = $kind].(price * qty)))");
expression.registerFunction("double", (n) => n * 2, "<n:n>");
const result = await expression.evaluate(order, { kind: "a" });

With jlens, from the npm package jlens-wasm:

import init, { Expression } from "jlens-wasm";

await init(); // once, before anything else

const expression = new Expression("$double($sum(items[type = $kind].(price * qty)))");
expression.registerFunction("double", (n) => n * 2, "<n:n>");
const result = expression.evaluate(order, { kind: "a" });

In Node.js and Deno, init takes the bytes of the .wasm file: see Loading the module.

The API, side by side

jsonata-jsjlens-wasm
jsonata(source)new Expression(source), after await init() once
await expression.evaluate(input, bindings)expression.evaluate(input, bindings, options). It is synchronous and returns the value; an await left in front of it still works
expression.evaluate(input, bindings, callback)No callback: the call returns the value or throws
expression.assign(name, value)No assign: pass the variable in the bindings of each evaluation
expression.registerFunction(name, implementation, signature)The same
expression.ast()expression.ast(), a tree of jlens’s own: each node has an id and a span where jsonata-js has a position
jsonata(source, { recover: true }) and expression.errors()The diagnostics of the language service
An error is a plain object with code, position, token and valueAn Error named JlensError with the same fields, the same codes and the same positions, plus the range start to end

The WebAssembly guide describes each of them.

What to check in your application

  • Asynchronous functions. A host function that returns a promise fails with U1002, and jlens does not plan to change that (Not planned). Fetch what the expression needs before evaluating it, and pass it in the bindings.
  • Input that is not plain JSON. jlens reads the input as JSON.stringify does: a Date arrives as its ISO 8601 string, so $type(d) is "string" where jsonata-js gives "object", and undefined fields and functions are left out (the input in WebAssembly).
  • Host functions receive copies. Arguments and results pass through JSON, so a function cannot change the values of the evaluation. this is undefined: a signature with - passes the context value as an argument (host functions).
  • Recursion that is too deep fails with D1011, at 500 levels by default, where jsonata-js throws a RangeError. The options of evaluate set this limit and the others (Limits and memory).
  • Objects with integer-like keys. JavaScript puts keys such as "1" and "2" first; jlens keeps the order in which an object was built. A result returned as a JavaScript object looks the same in both, as JavaScript orders it. The difference shows where the expression reads the order of an object it built, as in $keys({"b": 1, "2": 2}), which is ["b", "2"] here and ["2", "b"] in jsonata-js, and in the text evaluateJson returns.
  • Code that reads error messages. Match on code: jlens promises the codes, not the text.

What jlens adds

  • Explanations. evaluateWithAudit returns the result with the reason for it: which comparisons passed or failed, with their values (Explaining results).
  • Limits for expressions you did not write. A timeout, a step limit that is the same on every machine, size limits, and regular expressions that stop at them (ADR 0009). An evaluation ends with a result or a coded error.
  • One document for many evaluations. A Document is converted once and shared by a set of rules (Reusing a document). Performance compares both engines.
  • Checks before running. The language service completes and diagnoses expressions against a schema inferred from sample documents, and the command line checks and tests them (jlens check, jlens test).

Other platforms

The Python and Java packages have the API above in their language’s style, and the Rust crate is the engine itself. An expression moves between them, and to and from jsonata-js, unchanged.

Language overview

JSONata is a query and transformation language for JSON. An expression selects values from a document with location paths (Account.Order.Product), combines them with operators and functions ($sum(Product.(Price * Quantity))), and shapes the output with ordinary JSON syntax ({"total": ...}). It also has variables, functions and conditionals, so rules of any complexity can be written in it.

jlens implements JSONata 2.3 and is checked against the official test suite. Where it differs from the reference implementation, jsonata-js, Compatibility says so.

This reference is adapted from the JSONata documentation (© IBM Corp. and JSONata contributors, MIT license), reorganized and extended with jlens-specific notes. Every example in it is run against jlens by cargo xtask doc-check.

Reading the examples

Examples show an expression followed by its result after =>:

1 + 2
=> 3

When an example needs an input document, its first line names it. Most examples use one of three sample documents, listed at the end of this page:

input: address.json
Address.City
=> "Winchester"

A result of undefined means the expression produced nothing: JSONata’s empty sequence. The command line prints nothing for it, and the APIs return None or undefined.

Types

JSONata values have the JSON types plus one more:

TypeExamples
string"hello", 'hello', a template «hello {name}»
number42, -3.5, 1e6 (always a 64-bit float)
Booleantrue, false
nullnull
array[1, "two", null]
object{"name": "Fred", "age": 28}
function$uppercase, function($x) { $x * 2 }

JSONata is a superset of JSON. Every JSON document is a valid expression that evaluates to itself. A JSON template is therefore a good start for a transformation: replace its values with expressions.

input: address.json
{"name": FirstName & " " & Surname, "adult": Age >= 18, "phones": $count(Phone)}
=> {"name": "Fred Smith", "adult": true, "phones": 4}

Sequences

A path can match zero, one or many values, so JSONata expressions produce sequences. The rules for sequences shape every result:

  1. An empty sequence is nothing. It is not null, and it does not appear in the output: an object field whose value is an empty sequence is left out.
  2. A sequence of one value is that value. No array surrounds it.
  3. A sequence of several values is output as an array.
  4. Sequences are flattened. Values of nested sequences are pulled up into the outer one. Arrays from the input, or built with [...], keep their structure.
input: address.json
Phone[type = 'mobile'].number
=> "077 7700 1234"
input: address.json
Phone[type = 'office'].number
=> ["01962 001234", "01962 001235"]
input: address.json
{"fax": Phone[type = 'fax'].number, "name": FirstName}
=> {"name": "Fred"}

The second rule makes a single value and a one-element array interchangeable, which keeps expressions composable. When a consistent array is needed, the [] modifier keeps singleton results as arrays.

Comments

/* ... */ comments can appear anywhere whitespace can:

input: address.json
/* the person's full name */
FirstName & " " & Surname
=> "Fred Smith"

Comments that start with /** are documentation comments. jlens reads @label, @message and @id tags in them to describe checks in audits; see Audit annotations. Other JSONata implementations treat them as ordinary comments.

The rest of this reference

Sample documents

address.json:

{
  "FirstName": "Fred",
  "Surname": "Smith",
  "Age": 28,
  "Address": {
    "Street": "Hursley Park",
    "City": "Winchester",
    "Postcode": "SO21 2JN"
  },
  "Phone": [
    { "type": "home", "number": "0203 544 1234" },
    { "type": "office", "number": "01962 001234" },
    { "type": "office", "number": "01962 001235" },
    { "type": "mobile", "number": "077 7700 1234" }
  ],
  "Email": [
    {
      "type": "work",
      "address": ["fred.smith@my-work.com", "fsmith@my-work.com"]
    },
    {
      "type": "home",
      "address": ["freddy@my-social.com", "frederic.smith@very-serious.com"]
    }
  ],
  "Other": {
    "Over 18 ?": true,
    "Misc": null,
    "Alternative.Address": {
      "Street": "Brick Lane",
      "City": "London",
      "Postcode": "E1 6RF"
    }
  }
}

invoice.json:

{
    "Account": {
        "Account Name": "Firefly",
        "Order": [
            {
                "OrderID": "order103",
                "Product": [
                    {
                        "Product Name": "Bowler Hat",
                        "ProductID": 858383,
                        "SKU": "0406654608",
                        "Description": {
                            "Colour": "Purple",
                            "Width": 300,
                            "Height": 200,
                            "Depth": 210,
                            "Weight": 0.75
                        },
                        "Price": 34.45,
                        "Quantity": 2
                    },
                    {
                        "Product Name": "Trilby hat",
                        "ProductID": 858236,
                        "SKU": "0406634348",
                        "Description": {
                            "Colour": "Orange",
                            "Width": 300,
                            "Height": 200,
                            "Depth": 210,
                            "Weight": 0.6
                        },
                        "Price": 21.67,
                        "Quantity": 1
                    }
                ]
            },
            {
                "OrderID": "order104",
                "Product": [
                    {
                        "Product Name": "Bowler Hat",
                        "ProductID": 858383,
                        "SKU": "040657863",
                        "Description": {
                            "Colour": "Purple",
                            "Width": 300,
                            "Height": 200,
                            "Depth": 210,
                            "Weight": 0.75
                        },
                        "Price": 34.45,
                        "Quantity": 4
                    },
                    {
                        "ProductID": 345664,
                        "SKU": "0406654603",
                        "Product Name": "Cloak",
                        "Description": {
                            "Colour": "Black",
                            "Width": 30,
                            "Height": 20,
                            "Depth": 210,
                            "Weight": 2
                        },
                        "Price": 107.99,
                        "Quantity": 1
                    }
                ]
            }
        ]
    }
}

library.json:

{
    "library": {
        "books": [
            {
                "title": "Structure and Interpretation of Computer Programs",
                "authors": ["Abelson", "Sussman"],
                "isbn": "9780262510875",
                "price": 38.90,
                "copies": 2
            },
            {
                "title": "The C Programming Language",
                "authors": ["Kernighan", "Richie"],
                "isbn": "9780131103627",
                "price": 33.59,
                "copies": 3
            },
            {
                "title": "The AWK Programming Language",
                "authors": ["Aho", "Kernighan", "Weinberger"],
                "isbn": "9780201079814",
                "copies": 1
            },
            {
                "title": "Compilers: Principles, Techniques, and Tools",
                "authors": ["Aho", "Lam", "Sethi", "Ullman"],
                "isbn": "9780201100884",
                "price": 23.38,
                "copies": 1
            }
        ],
        "loans": [
            {
                "customer": "10001",
                "isbn": "9780262510875",
                "return": "2016-12-05"
            },
            {
                "customer": "10003",
                "isbn": "9780201100884",
                "return": "2016-10-22"
            },
            {
                "customer": "10003",
                "isbn": "9780262510875",
                "return": "2016-12-22"
            }
        ],
        "customers": [
            {
                "id": "10001",
                "name": "Joe Doe",
                "address": {
                    "street": "2 Long Road",
                    "city": "Winchester",
                    "postcode": "SO22 5PU"
                }
            },
            {
                "id": "10002",
                "name": "Fred Bloggs",
                "address": {
                    "street": "56 Letsby Avenue",
                    "city": "Winchester",
                    "postcode": "SO22 4WD"
                }
            },
            {
                "id": "10003",
                "name": "Jason Arthur",
                "address": {
                    "street": "1 Preddy Gate",
                    "city": "Southampton",
                    "postcode": "SO14 0MG"
                }
            }
        ]
    }
}

Paths

A location path selects values from the input document. Field names separated by . navigate into nested objects, and every array along the way is searched item by item.

input: address.json
Surname
=> "Smith"
input: address.json
Address.City
=> "Winchester"

A path that matches null returns it. A path that matches nothing returns nothing (an empty sequence), never an error: missing data is normal.

input: address.json
Other.Misc
=> null
input: address.json
Other.Nothing
=> undefined

Field names that are not plain identifiers go between backquotes:

input: address.json
Other.`Over 18 ?`
=> true

When a step selects an array, the following steps apply to each of its items, and the results are collected:

input: address.json
Phone.number
=> ["0203 544 1234", "01962 001234", "01962 001235", "077 7700 1234"]

A number in square brackets selects an item by position, from 0. Negative positions count from the end, and non-integer positions are rounded down. A position past the end selects nothing.

input: address.json
Phone[0]
=> {"type": "home", "number": "0203 544 1234"}
input: address.json
Phone[-1].number
=> "077 7700 1234"
input: address.json
Phone[8]
=> undefined

An array of positions selects several items:

input: address.json
Phone[[0, 2]].number
=> ["0203 544 1234", "01962 001235"]
input: address.json
Phone[[0..1]].number
=> ["0203 544 1234", "01962 001234"]

The index applies to the step it follows, not to the whole path so far. Phone.number[0] takes the first number of each phone. Parentheses apply the index to the whole result:

input: address.json
Phone.number[0]
=> ["0203 544 1234", "01962 001234", "01962 001235", "077 7700 1234"]
input: address.json
(Phone.number)[0]
=> "0203 544 1234"

Predicates

Square brackets around any other expression filter the items: an item is kept when the expression, evaluated with the item as context, is true. Values that are not Booleans are converted as by $boolean.

input: address.json
Phone[type = 'mobile'].number
=> "077 7700 1234"
input: invoice.json
Account.Order.Product[Price > 30 and Quantity > 1].`Product Name`
=> ["Bowler Hat", "Bowler Hat"]
input: library.json
library.books["Aho" in authors].title
=> ["The AWK Programming Language", "Compilers: Principles, Techniques, and Tools"]

Always getting an array

Because a single value and a one-item sequence are the same (see Sequences), a path can return a value or an array depending on the data. Empty square brackets [] on any step keep the result an array:

input: address.json
Address[].City
=> ["Winchester"]
input: address.json
Phone[type = 'home'].number[]
=> ["0203 544 1234"]

The context: $ and $$

$ is the context value: the item a step is evaluated against. At the start of an expression it is the whole input document, which is how a top-level array is indexed. $$ is always the root of the input, wherever the evaluation is.

input: [{"ref": [1, 2]}, {"ref": [3, 4]}]
$[0].ref
=> [1, 2]
input: [{"ref": [1, 2]}, {"ref": [3, 4]}]
$.ref
=> [1, 2, 3, 4]

The nested arrays of the last example were flattened into one sequence. To keep the structure, use an array constructor: $.[ref].

input: address.json
Phone[type = 'mobile'].($$.FirstName & ": " & number)
=> "Fred: 077 7700 1234"

Wildcards

* selects the values of all the fields of an object:

input: address.json
Address.*
=> ["Hursley Park", "Winchester", "SO21 2JN"]
input: address.json
*.Postcode
=> "SO21 2JN"

** selects descendants at any depth:

input: address.json
**.Postcode
=> ["SO21 2JN", "E1 6RF"]

** gives no functions, where * gives those an object holds:

$count({"a": {"f": $sum, "b": 2}}.**)
=> 3

Path stages

A path is a pipeline of stages. Each stage takes the sequence from the previous one:

StageSyntaxAction
Mapseq . exprEvaluates expr for each item, and flattens the results
Filterseq [ expr ]Keeps the items for which expr is true (or the positions expr gives)
Sortseq ^( keys )Sorts the items; see Sorting
Indexseq # $varBinds the position of each item to $var
Joinseq @ $varBinds each item to $var, keeping the previous context
Groupseq { key: value, … }Groups the items into one object; see Grouping

A filter binds more tightly than a map, so books.authors[0] is the first author of each book. Parentheses change the grouping, as (books.authors)[0] does. Parentheses also end the scope of variables bound inside them.

Mapping with expressions

Any expression can be a step, not just a field name. Its context is each item in turn:

input: invoice.json
Account.Order.Product.(Price * Quantity)
=> [68.9, 21.67, 137.8, 107.99]
input: invoice.json
Account.Order.OrderID.$uppercase()
=> ["ORDER103", "ORDER104"]

Positions: #

#$i binds the position of each item, counted before later filters, to $i:

input: library.json
library.books#$i["Kernighan" in authors].{"title": title, "index": $i}
=> [
  {"title": "The C Programming Language", "index": 1},
  {"title": "The AWK Programming Language", "index": 2}
]

Joins: @

@$v binds each item to $v and keeps the context where it was, so the next step navigates from the same place. That cross-references arrays like a join in a database:

input: library.json
library.loans@$l.books@$b[$l.isbn = $b.isbn].{"title": $b.title, "customer": $l.customer}
=> [
  {"title": "Structure and Interpretation of Computer Programs", "customer": "10001"},
  {"title": "Compilers: Principles, Techniques, and Tools", "customer": "10003"},
  {"title": "Structure and Interpretation of Computer Programs", "customer": "10003"}
]

Parents: %

% selects the parent of the context value: the object whose field holds it. %.% is the grandparent. The parent is worked out from the path when the expression is compiled, so % only works in paths that reach the value through its parent (otherwise: error S0217).

input: invoice.json
Account.Order.Product.{"product": `Product Name`, "order": %.OrderID, "account": %.%.`Account Name`}
=> [
  {"product": "Bowler Hat", "order": "order103", "account": "Firefly"},
  {"product": "Trilby hat", "order": "order103", "account": "Firefly"},
  {"product": "Bowler Hat", "order": "order104", "account": "Firefly"},
  {"product": "Cloak", "order": "order104", "account": "Firefly"}
]

Building results

The output of an expression can have any shape. Array and object constructors use JSON syntax, with expressions wherever values (and object keys) go.

Arrays

Square brackets build an array of the values of the expressions inside them:

input: address.json
[Address.City, Other.`Alternative.Address`.City]
=> ["Winchester", "London"]

Unlike a sequence, an array built with [...] keeps its structure: it is neither flattened nor unwrapped when it has a single item. As a path step, it builds one array per context item:

input: address.json
Email.address
=> ["fred.smith@my-work.com", "fsmith@my-work.com", "freddy@my-social.com", "frederic.smith@very-serious.com"]
input: address.json
Email.[address]
=> [
  ["fred.smith@my-work.com", "fsmith@my-work.com"],
  ["freddy@my-social.com", "frederic.smith@very-serious.com"]
]

An array constructor can also select several paths at once, as a more precise alternative to wildcards:

input: address.json
[Address, Other.`Alternative.Address`].City
=> ["Winchester", "London"]

Ranges

Inside an array constructor, from..to produces the integers from from to to, both included. Both ends must be integers (error T2003, T2004), and a range can have at most 10 million items (D2014).

[1..5]
=> [1, 2, 3, 4, 5]
[1..3, 7..9]
=> [1, 2, 3, 7, 8, 9]
[1..5].($ * $)
=> [1, 4, 9, 16, 25]
input: address.json
[1..$count(Phone)].("Phone " & $)
=> ["Phone 1", "Phone 2", "Phone 3", "Phone 4"]

Objects

Braces build an object from key: value pairs. Keys are expressions that must evaluate to strings (error T1003); values are any expressions. Fields whose value is nothing are left out.

input: address.json
{"name": FirstName, "city": Address.City, "fax": Phone[type = 'fax'].number}
=> {"name": "Fred", "city": "Winchester"}

Where the constructor appears changes what it does:

  • After . it is a map step and builds one object per item:

    input: address.json
    Phone.{type: number}
    => [
      {"home": "0203 544 1234"},
      {"office": "01962 001234"},
      {"office": "01962 001235"},
      {"mobile": "077 7700 1234"}
    ]
    
  • Directly after a path (no .) it groups the items into a single object. Values for the same key are collected together; see Grouping.

    input: address.json
    Phone{type: number}
    => {
      "home": "0203 544 1234",
      "office": ["01962 001234", "01962 001235"],
      "mobile": "077 7700 1234"
    }
    

    With [], every group is an array, whatever its size:

    input: address.json
    Phone{type: number[]}
    => {
      "home": ["0203 544 1234"],
      "office": ["01962 001234", "01962 001235"],
      "mobile": ["077 7700 1234"]
    }
    

JSON literals

Values of every JSON type can be written as they are in JSON: strings (with JSON escapes, and either quote character), numbers, true, false, null, arrays and objects. Because JSONata is a superset of JSON, a JSON document makes a good template for the output.

input: invoice.json
{
  "account": Account.`Account Name`,
  "orders": Account.Order.{
    "id": OrderID,
    "total": $round($sum(Product.(Price * Quantity)), 2),
    "items": $count(Product)
  },
  "currency": "EUR"
}
=> {
  "account": "Firefly",
  "orders": [
    {"id": "order103", "total": 90.57, "items": 2},
    {"id": "order104", "total": 245.79, "items": 2}
  ],
  "currency": "EUR"
}

Operators

Arithmetic

OperatorMeaning
+Addition
-Subtraction, and negation in prefix form (-x)
*Multiplication
/Division
%Remainder, with the sign of the left operand

Both operands must be numbers (error T2001, T2002), and a result that is not finite (such as 1/0) is an error (D1001). If either operand is nothing, the result is nothing.

5 + 2 * 3
=> 11
5 / 2
=> 2.5
-7 % 3
=> -1
input: invoice.json
Account.Order[0].Product[0].(Price * Quantity)
=> 68.9
"5" + 1
=> error T2001
missing + 1
=> undefined

Numbers are 64-bit floats, as in JavaScript, and results are printed the way JavaScript prints them:

0.1 + 0.2
=> 0.30000000000000004

Comparison

OperatorMeaning
=Equal: same type and value; arrays and objects are compared deeply
!=Not equal
<, <=, >, >=Order of numbers, or of strings (by Unicode code point)
inThe left value is one of the values on the right

= and != never fail: values of different types are simply not equal. The ordering operators need two numbers or two strings (errors T2009, T2010). Comparing with nothing gives false.

1 + 1 = 2
=> true
"1" = 1
=> false
{"a": [1, 2]} = {"a": [1, 2]}
=> true
"apple" < "banana"
=> true
"world" in ["hello", "world"]
=> true
"hello" in "hello"
=> true
input: address.json
"01962 001234" in Phone.number
=> true

Boolean

and and or convert their operands to Booleans as $boolean does, and stop as soon as the result is known: the right side of false and x is never evaluated. Negation is a function, $not.

input: library.json
library.books["Aho" in authors and price < 50].title
=> "Compilers: Principles, Techniques, and Tools"

The other book by Aho has no price, and comparing nothing with 50 is false.

0 or "yes"
=> true
$not(true and false)
=> true

Strings

& joins strings. It is the only operator that converts its operands: non-strings become strings as by $string, and nothing becomes the empty string.

input: address.json
FirstName & " " & Surname
=> "Fred Smith"
5 & 0 & true & missing
=> "50true"

Template strings

A template string is literal text with expressions in braces, written «...», or <<...>> where guillemets are hard to type (JSONata 2.3). Each expression’s value joins the text as & joins it: a string as it is, other values as by $string, nothing as the empty string.

input: address.json
«{FirstName} {Surname} has {$count(Phone)} phones»
=> "Fred Smith has 4 phones"

The text is kept as written, whitespace and quotes included. A backslash escapes what it escapes in a string literal, and {, }, <, >, « and » too. A } in the text must be escaped (S0108), and the first >> closes a <<...>> template, so text that ends with > escapes it:

input: address.json
<<<b>{Surname}</b\>>>
=> "<b>Smith</b>"

Between the braces goes any expression, another template among them; a block of several needs its own parentheses, {($x := 2; $x * 3)}, and {} adds nothing. In a path, a template is a string built for each item, never a field name:

input: address.json
Phone[type = "office"].«{type}: {number}»
=> ["office: 01962 001234", "office: 01962 001235"]

<< opens a template only where an operand starts. After an operand it is the less-than operator, so "a"<<<b>> compares "a" with the template <<b>>.

Conditionals

condition ? then : else evaluates then when the condition is true, and else otherwise. The condition is converted to a Boolean. Without an else part, a false condition produces nothing.

input: invoice.json
Account.Order.Product.(Price > 100 ? "premium" : "standard")
=> ["standard", "standard", "standard", "premium"]
false ? "yes"
=> undefined

Defaults

OperatorResult
a ?: ba if it is true as a Boolean, else b. A fallback for missing or falsy values (null, false, 0, "")
a ?? ba if it exists (is not nothing), else b. A fallback only for missing values
input: address.json
Other.Misc ?: "n/a"
=> "n/a"
input: address.json
Other.Misc ?? "n/a"
=> null
0 ?? 1
=> 0

Chaining: ~>

value ~> $f(args) calls $f(value, args). Chains read left to right instead of inside out:

input: invoice.json
Account.Order.Product.(Price * Quantity) ~> $sum() ~> $round(1)
=> 336.4
"  Hello  World  " ~> $trim() ~> $uppercase()
=> "HELLO WORLD"

With functions on both sides, ~> composes them into a new function; see Function composition. A regular expression on the right tests a string, which is useful in filters.

Other operators

OperatorMeaningSee
:=Binds a variableVariables
..Integer range, in array constructorsRanges
|location|update, delete|Transform a copy of an objectTransforms
., [...], ^(...), #, @, %, *, **Path stagesPaths

Precedence

From the tightest binding to the loosest:

OperatorsAssociativity
Function call f(...), filter [...], #, @left
.left
Grouping {...} after a pathleft
*, /, %left
+, -, &left
=, !=, <, <=, >, >=, in, ~>, ^(...), ?:, ??left
andleft
orleft
? :right
:=right

Unary minus binds more tightly than any binary operator. Parentheses override precedence:

(5 + 3) * 4
=> 32
1 < 2 and 2 < 3 or false
=> true

Sorting, grouping and aggregation

Sorting

The order-by stage ^(...) sorts the items of a path. Sort keys are expressions evaluated against each item, and they must give numbers or strings. Strings sort by Unicode code point. A key prefixed with > sorts in descending order; <, the default, sorts in ascending order. Further keys, separated by commas, break ties. The sort is stable.

input: invoice.json
Account.Order.Product^(Price).`Product Name`
=> ["Trilby hat", "Bowler Hat", "Bowler Hat", "Cloak"]
input: invoice.json
Account.Order.Product^(>Price, <Quantity).{"name": `Product Name`, "qty": Quantity}
=> [
  {"name": "Cloak", "qty": 1},
  {"name": "Bowler Hat", "qty": 2},
  {"name": "Bowler Hat", "qty": 4},
  {"name": "Trilby hat", "qty": 1}
]
input: invoice.json
Account.Order.Product^(Price * Quantity).(Price * Quantity)
=> [21.67, 68.9, 107.99, 137.8]

$sort sorts an array with a comparison function, for orders that keys cannot express.

Grouping

An object constructor directly after a path (without .) groups the items: it evaluates the key for each item, and items with the same key fall into the same group. Then it evaluates the value once per group, with the group’s items as context. Aggregations therefore work per group:

input: invoice.json
Account.Order.Product{`Product Name`: Price}
=> {"Bowler Hat": [34.45, 34.45], "Trilby hat": 21.67, "Cloak": 107.99}
input: invoice.json
Account.Order.Product{`Product Name`: $round($sum($.(Price * Quantity)), 2)}
=> {"Bowler Hat": 206.7, "Trilby hat": 21.67, "Cloak": 107.99}

The value expression runs against the whole group. A path in it therefore collects values from all the group’s items. To build one object per item, map over the group with $.:

input: invoice.json
Account.Order.Product{`Product Name`: {"price": Price, "qty": Quantity}}
=> {
  "Bowler Hat": {"price": [34.45, 34.45], "qty": [2, 4]},
  "Trilby hat": {"price": 21.67, "qty": 1},
  "Cloak": {"price": 107.99, "qty": 1}
}
input: invoice.json
Account.Order.Product{`Product Name`: $.{"price": Price, "qty": Quantity}}
=> {
  "Bowler Hat": [{"price": 34.45, "qty": 2}, {"price": 34.45, "qty": 4}],
  "Trilby hat": {"price": 21.67, "qty": 1},
  "Cloak": {"price": 107.99, "qty": 1}
}

Keys must be strings (error T1003). Several key/value pairs can group the same items in different ways, and a group that evaluates to nothing is left out.

input: library.json
library.books{
  "cheap": $count($[price < 30]),
  "expensive": $count($[price >= 30]),
  "unpriced": $count($[$not($exists(price))])
}
=> {"cheap": 1, "expensive": 2, "unpriced": 1}

Aggregation

Aggregation functions reduce an array to one value:

input: invoice.json
$sum(Account.Order.Product.(Price * Quantity))
=> 336.36
input: invoice.json
{
  "orders": $count(Account.Order),
  "dearest": $max(Account.Order.Product.Price),
  "average quantity": $average(Account.Order.Product.Quantity)
}
=> {"orders": 2, "dearest": 107.99, "average quantity": 2}
input: invoice.json
$join(Account.Order.Product.`Product Name`, ", ")
=> "Bowler Hat, Trilby hat, Bowler Hat, Cloak"

Programming

JSONata is a functional language. Values are immutable, functions are values, and everything is an expression.

Blocks

Parentheses group expressions separated by ;. The expressions are evaluated in order, and the block’s value is the value of the last one. A block is also a scope for variables.

(1 + 2; "ignored"; 10 * 2)
=> 20

Variables

A name that starts with $ is a variable. $name := value binds a variable, and its value is the bound value. The binding is visible in the rest of the block and in nested blocks, but not outside the block.

input: invoice.json
Account.Order.Product.(
  $total := Price * Quantity;
  $tax := $total * 0.2;
  $round($total + $tax, 2)
)
=> [82.68, 26, 165.36, 129.59]
($x := 1; ($x := 2); $x)
=> 1

Predefined variables:

  • $ is the context value; see Paths.
  • $$ is the root of the input.
  • The built-in functions ($sum, $string, …) are variables too, so a binding can replace one in its scope.

Applications can define more variables when they evaluate an expression: bindings, such as jlens eval --bindings, Bindings in Rust, or the bindings argument in JavaScript.

bindings: {"limit": 100, "rate": 0.2}
$limit * (1 + $rate)
=> 120

Functions

Calling functions

A function is called with its arguments in parentheses:

$substring("hello world", 0, 5)
=> "hello"

Many built-in functions use the context value when their first argument is omitted (their signature marks that argument with -). That makes them usable as path steps:

input: invoice.json
Account.Order.OrderID.$uppercase()
=> ["ORDER103", "ORDER104"]

Defining functions

function($a, $b) { body } defines a function. λ can be written instead of function. Functions are values: bind them to variables, pass them to other functions, return them.

(
  $volume := function($l, $w, $h) { $l * $w * $h };
  $volume(10, 10, 5)
)
=> 500
λ($x) { $x * 2 }(21)
=> 42

Missing arguments are undefined inside the function, and extra arguments are ignored.

Signatures

An optional signature after the parameter list declares the types of the arguments and of the result. Arguments are then checked when the function is called (errors T0410 and T0412).

(
  $repeat := function($s, $n)<sn:s> { $join([1..$n].($s)) };
  $repeat("ab", 3)
)
=> "ababab"
(
  $repeat := function($s, $n)<sn:s> { $join([1..$n].($s)) };
  $repeat(3, "ab")
)
=> error T0410

A signature is <params:result>, with one symbol per parameter:

SymbolType
bBoolean
nnumber
sstring
lnull
aarray; a<n> is an array of numbers
oobject
ffunction
(sn)a choice: string or number
u(bnsl): any simple value
j(bnsloa): any JSON value
xany value, functions included

These modifiers can follow a symbol:

  • ? makes the parameter optional.
  • + takes one or more arguments of the type.
  • - takes the context value when the argument is missing.

A single value is accepted where an array is expected. For example, $sum has the signature <a<n>:n> and $length has <s-:n>. The function reference gives the signature of every built-in function.

Recursion and tail calls

A function bound to a variable can call itself through it:

(
  $factorial := function($n) { $n <= 1 ? 1 : $n * $factorial($n - 1) };
  $factorial(10)
)
=> 3628800

Each nested call uses stack, and evaluation stops with D1011 past a depth limit (see Guardrails). A call in tail position, the last thing a function does, does not nest. jlens runs it as a loop, so tail-recursive functions can iterate any number of times:

(
  $sumTo := function($n, $acc) { $n = 0 ? $acc : $sumTo($n - 1, $acc + $n) };
  $sumTo(100000, 0)
)
=> 5000050000

Closures

A function remembers the variables and the context value of the place where it was defined:

(
  $multiplier := function($k) { function($x) { $x * $k } };
  $triple := $multiplier(3);
  [$triple(2), $triple(5)]
)
=> [6, 15]
input: invoice.json
Account.(
  $account := function() { $.`Account Name` };
  Order[OrderID = 'order104'].Product.{"account": $account(), "product": `Product Name`}
)
=> [
  {"account": "Firefly", "product": "Bowler Hat"},
  {"account": "Firefly", "product": "Cloak"}
]

Higher-order functions

Functions that take or return functions are called higher-order. The library has several: $map, $filter, $reduce, $sift, $single and $sort.

(
  $twice := function($f) { function($x) { $f($f($x)) } };
  $twice(function($y) { $y + 3 })(7)
)
=> 13

Partial application

Calling a function with ? in place of some arguments returns a new function that takes the missing ones:

(
  $first5 := $substring(?, 0, 5);
  $first5("Hello, World")
)
=> "Hello"
(
  $firstN := $substring(?, 0, ?);
  $firstN("Hello, World", 3)
)
=> "Hel"

Function composition

When both sides of ~> are functions, the result is their composition: a function that applies the left one, then the right one.

(
  $normalize := $trim ~> $uppercase;
  $normalize("   Some   Words   ")
)
=> "SOME WORDS"
input: address.json
(
  $first5Capitalized := $substring(?, 0, 5) ~> $uppercase(?);
  $first5Capitalized(Address.City)
)
=> "WINCH"

Conditional logic

The conditional operator ? : and the default operators ?: and ?? cover if/then/else. Nested conditionals read like an else if chain:

input: invoice.json
Account.Order.Product.(
  Price > 100 ? "premium" :
  Price > 30 ? "standard" :
  "budget"
)
=> ["standard", "budget", "standard", "premium"]

Transforms

The transform operator |location|update| or |location|update, delete| produces a function. That function copies its argument and, in the copy, changes every object that location matches:

  • update must evaluate to an object. Its fields are merged into each matched object, as $merge does. update is evaluated against the matched object.
  • delete (optional) names the fields to remove: a string or an array of strings.

The original value is not modified.

input: invoice.json
(
  $copy := $ ~> |Account.Order.Product|{"Price": $round(Price * 1.2, 2)}, ["SKU", "Description"]|;
  $copy.Account.Order[0].Product
)
=> [
  {"Product Name": "Bowler Hat", "ProductID": 858383, "Price": 41.34, "Quantity": 2},
  {"Product Name": "Trilby hat", "ProductID": 858236, "Price": 26, "Quantity": 1}
]

Updates see the original values. Here Total uses the price before the 20% increase:

{"Price": 10, "Quantity": 3} ~> |$|{"Price": Price * 1.2, "Total": Price * Quantity}|
=> {"Price": 12, "Quantity": 3, "Total": 30}

location can match only objects of the copy. One that reaches outside it, through $$ or a variable bound outside the transform, or that matches a function, is an error (D1014), and nothing is changed:

input: {"settings": {"limit": 10}}
{} ~> |$$.settings|{"limit": 0}|
=> error D1014

The copy is made by the built-in $clone, or by a host function named clone; a $clone bound in the expression is not used, so a transform never changes its input.

A transform is a function, so it can be bound to a variable and reused, or chained with other transforms. An update that would make an object contain itself is an error (U1001) in jlens; see Compatibility.

Comments and annotations

/* ... */ comments are ignored. jlens reads documentation comments (/** ... */) placed before a subexpression as audit annotations: labels and messages that explain the checks of a rule.

Regular expressions

A regular expression is written between slashes, optionally followed by flags:

/pattern/flags
FlagMeaning
iIgnore case
mMulti-line: ^ and $ match at line breaks
uUnicode mode: \p{…} and the other escapes of Unicode text. A jlens extension
vUnicode mode with operations on classes and properties of strings. A jlens extension

The flags come in any order, each at most once; u and v exclude each other, as in JavaScript. jsonata-js knows only i and m, and rejects an expression with u or v (S0202), so an expression that uses them runs in jlens alone.

The syntax and semantics are those of JavaScript regular expressions (ECMAScript). They include character classes, quantifiers (greedy and lazy), groups, backreferences, lookahead and lookbehind, and Unicode escapes. jlens uses the regress engine, which follows the ECMAScript specification. An invalid pattern fails with S0302.

Like JavaScript’s, the engine backtracks, so some patterns take exponential time on inputs they almost match: /^(a+)+$/ on thirty a followed by ! tries half a billion ways to split the run. When the evaluation has a timeout or a cancellation token, a match stops with D1012 or U1003 like any other step (ADR 0009). Set a timeout when the expressions come from users.

Unicode text

A pattern matches characters, in any script. Without a flag, it can name a letter outside ASCII only by writing it: \w is [A-Za-z0-9_], \d is [0-9] and \b sits between those characters and the others, as in JavaScript. The flags u and v add the escapes of Unicode properties:

EscapeMatches
\p{L}, \p{Lu}, \p{Ll}A letter, an uppercase letter, a lowercase letter, of any script
\p{N}, \p{Nd}A number, a decimal digit, of any script
\p{M}A combining mark, such as an accent written apart from its letter
\p{P}, \p{S}, \p{Z}Punctuation, a symbol, a separator
\p{Script=Greek}, \p{sc=Cyrl}A character of a script (Latin, Greek, Cyrillic, Han, Arabic…)
\p{Script_Extensions=Han}, \p{scx=Hira}A character used in a script, those shared between scripts included
\P{…}A character without the property
\u{1F600}A character by its code point
differs: jsonata-js rejects the flag u (S0202)
$match("Café, Ωμέγα, Москва, 東京", /\p{L}+/u).match
=> ["Café", "Ωμέγα", "Москва", "東京"]

\w, \d and \b stay ASCII with u and v. A word in any script is [\p{L}\p{N}_]+:

differs: jsonata-js rejects the flag u (S0202)
{
  "ascii": $match("naïve café", /\w+/u).match,
  "words": $match("naïve café", /[\p{L}\p{N}_]+/u).match
}
=> {"ascii": ["na", "ve", "caf"], "words": ["naïve", "café"]}

A text can write an accented letter as one character, é, or as a letter followed by a combining mark, e and U+0301; both look the same. \p{L} matches the letter, not the mark, so a pattern for words in such text takes the marks too, [\p{L}\p{M}]+:

differs: jsonata-js rejects the flag u (S0202)
[$match("Café", /\p{L}+/u).match, $match("Café", /[\p{L}\p{M}]+/u).match]
=> ["Cafe", "Café"]

i ignores case in any script, with or without u. With u or v it follows Unicode’s case folding, so that /k/iu also matches the Kelvin sign K (U+212A), which JavaScript’s default mode keeps apart.

The flag v adds operations on classes: -- takes the characters of one class out of another, && keeps those in both, and classes nest. It also adds the properties of strings, which match a sequence of characters, such as \p{RGI_Emoji} for an emoji with its skin tone, a flag or a family:

differs: jsonata-js rejects the flag v (S0202)
$match("Ωmega, Ωμέγα, Омега", /[\p{L}--\p{Script=Latin}]+/v).match
=> ["Ω", "Ωμέγα", "Омега"]
differs: jsonata-js rejects the flag v (S0202)
$match("ok 👍🏽 🇧🇷", /\p{RGI_Emoji}/v).[match, index]
=> [["👍🏽", 3], ["🇧🇷", 8]]

The positions count UTF-16 code units, as in JavaScript: 👍🏽 is two characters outside the Basic Multilingual Plane, four units. With v, the characters ( ) [ ] { } / - \ | are escaped inside a class, and doubled punctuation such as && or !! is reserved, so a pattern written for u can be a syntax error (S0302) with v:

differs: jsonata-js rejects the flags u and v (S0202)
[$match("a-b", /[a-]+/u).match, $match("a-b", /[a\-]+/v).match]
=> ["a-", "a-"]

Functions that take a regular expression

  • $contains tests whether a string matches.
  • $match returns the matches, with positions and groups.
  • $replace replaces matches, with references to groups.
  • $split splits a string around matches.
input: address.json
Email.address[$contains($, /@my-work\./)]
=> ["fred.smith@my-work.com", "fsmith@my-work.com"]
$replace("2024-03-15", /(\d+)-(\d+)-(\d+)/, "$3/$2/$1")
=> "15/03/2024"

Matching in predicates

A regular expression is a function: applied to a string, it returns the first match, or nothing. With the chain operator ~>, that makes a compact test in a filter:

input: invoice.json
Account.Order.Product[`Product Name` ~> /hat/i].`Product Name`
=> ["Bowler Hat", "Trilby hat", "Bowler Hat"]

Matcher functions

Called directly, a regular expression returns an object describing the first match:

  • match: the matched text;
  • start and end: its positions;
  • groups: the captured texts;
  • next: a function that returns the next match, or nothing.
(
  $matcher := /[a-z]*an[a-z]*/i;
  $m := $matcher("A man, a plan, a canal, Panama!");
  [$m.match, $m.start, $m.end, $m.next().match]
)
=> ["man", 2, 5, "plan"]

$contains, $match, $replace and $split only rely on this contract. Any function that returns such objects can therefore stand in for a regular expression, for example a lambda that implements a custom matching rule.

Positions in match objects are character offsets as JavaScript counts them, in UTF-16 code units. A character outside the Basic Multilingual Plane counts as two.


Adapted from the JSONata documentation (MIT license).

Dates and times

JSON has no date type. Timestamps are usually strings in ISO 8601 format ("2018-12-10T13:45:00.000Z") or numbers of milliseconds since the Unix epoch. JSONata works with both:

FunctionPurpose
$now()The evaluation time, as ISO 8601 or formatted
$millis()The evaluation time, in milliseconds
$fromMillis(ms, picture?, timezone?)Milliseconds to a formatted timestamp
$toMillis(timestamp, picture?)A timestamp to milliseconds

The evaluation time is captured once, when the evaluation starts. Every $now() and $millis() in an expression returns that same value:

input: invoice.json
(
  $start := $now();
  $total := $sum(Account.Order.Product.(Price * Quantity));
  $now() = $start
)
=> true

Durations are differences between millisecond values:

($toMillis("2018-12-10T18:00:00Z") - $toMillis("2018-12-10T09:30:00Z")) / 3600000
=> 8.5

Picture strings

Pictures describe other formats, both for formatting ($fromMillis, $now) and for parsing ($toMillis). The syntax is that of XPath fn:format-dateTime. Text is copied as is, and components in square brackets stand for parts of the timestamp:

ComponentMeaningDefault presentation
[Y]year1
[M]month of the year1
[D]day of the month1
[d]day of the year1
[F]day of the weekn (name)
[W]ISO week of the year1
[w]week of the month1
[X], [x]ISO week-numbering year, month of the week-numbering year1
[H]hour, 0–231
[h]hour, 1–121
[P]am or pmn
[m]minutes01
[s]seconds01
[f]fractions of a second1
[Z]time zone offset, +01:0001:01
[z]time zone as GMT+01:0001:01

A presentation modifier after the component letter chooses how it is written:

ModifierOutput
1, 01, 001decimal digits, padded to the width shown
#1digits with no padding ([h#1])
N, n, Nnthe name, in upper, lower or title case (months, days, am/pm)
w, W, Wwthe number in words
I, iRoman numerals
o after the presentationan ordinal: 1st, first
,min-maxthe minimum and maximum width ([MNn,3-3] gives Jan), at most 100 (D3142 above)

Literal square brackets are written [[ and ]].

$fromMillis(1544450400000, "[D01]/[M01]/[Y0001] [H01]:[m01]")
=> "10/12/2018 14:00"
$fromMillis(1544450400000, "[FNn], [D1o] [MNn] [YI]")
=> "Monday, 10th December MMXVIII"
$fromMillis(1544450400000, "[MNn,3-3] [D], [h]:[m01] [P]")
=> "Dec 10, 2:00 pm"
$fromMillis(1544450400000, "[Y]-[M01]-[D01]T[H01]:[m01]:[s01][Z]", "+0530")
=> "2018-12-10T19:30:00+05:30"

A negative timezone applies its sign to the hours and the minutes:

$fromMillis(0, "[H01]:[m01][Z]", "-0330")
=> "20:30-03:30"

Fractional seconds are the digits of the fraction, cut on the right without rounding: [f01] writes two, and [f] as many as there are, without the zeros at the end.

$fromMillis(1033, "[s].[f01] [f]")
=> "01.03 033"

A timezone that is not a number is an error:

differs: jsonata-js writes "NaN" in every component
$fromMillis(1544450400000, "[Y]", "CET")
=> error D3150

Parsing

$toMillis parses with the same pictures. Parts missing from the picture take default values: the start of the year, the month or the day.

$toMillis("10/12/2018", "[D]/[M]/[Y]") ~> $fromMillis("[M]/[D]/[Y]")
=> "12/10/2018"
$toMillis("Monday, 10th December 2018", "[FNn], [D1o] [MNn] [Y]")
=> 1544400000000
$toMillis("2018-12-10 14:00 +01:00", "[Y]-[M]-[D] [H]:[m] [Z]") ~> $fromMillis()
=> "2018-12-10T13:00:00.000Z"

The timestamp is matched without regard to case, so names and roman numerals are read in any case:

differs: jsonata-js reads only the name in title case, "April", and fails with D3136
$toMillis("27 APRIL 2008", "[D1] [MN] [Y0001]") ~> $fromMillis("[Y]-[M01]-[D01]")
=> "2008-04-27"

A timestamp that does not match the picture gives no date. Matching takes time proportional to the length of the timestamp times the parts of the picture, however the picture is built, and a timestamp whose length times the parts passes a million gives no date either.


Adapted from the JSONata documentation (MIT license).

Function reference

jlens implements every built-in function of JSONata 2.3. Each function has a signature that describes its parameters and result, for example <s-nn?:s>:

SymbolMeaning
s n b l ostring, number, boolean, null, object
aarray; a single value is wrapped in an array
a<n>array of numbers (any type can be given in angle brackets)
ffunction
jany JSON value; x any value
(sf)either of the types
?optional parameter
+one or more
-when the argument is missing, the context value is used
:sthe result type

Arguments that do not match the signature raise T0410 (wrong type), T0411 (the context value has the wrong type) or T0412 (an array item has the wrong type).

String functions

Details and examples: String functions.

FunctionSignatureDescription
$string($arg, $prettify)<x-b?:s>Casts a value to a string; objects and arrays become JSON
$substring($str, $start, $length)<s-nn?:s>Characters from a start position, optionally limited to a length
$substringBefore($str, $chars)<s-s:s>The part of a string before the first occurrence of a substring
$substringAfter($str, $chars)<s-s:s>The part of a string after the first occurrence of a substring
$lowercase($str)<s-:s>Converts a string to lower case
$uppercase($str)<s-:s>Converts a string to upper case
$length($str)<s-:n>Number of characters in a string
$trim($str)<s-:s>Normalizes and trims whitespace
$pad($str, $width, $char)<s-ns?:s>Pads a string to a width; positive pads on the right, negative on the left
$match($str, $regex, $limit)<s-f<s:o>n?:a<o>>Matches a regular expression, returning the matches with their positions and groups
$contains($str, $token)<s-(sf):b>Whether a string contains a substring or matches a regular expression
$replace($str, $pattern, $replacement, $limit)<s-(sf)(sf)n?:s>Replaces occurrences of a substring or regular expression
$split($str, $separator, $limit)<s-(sf)n?:a<s>>Splits a string by a separator or regular expression
$join($strs, $separator)<a<s>s?:s>Joins an array of strings with an optional separator

Numeric functions

Details and examples: Numeric functions.

FunctionSignatureDescription
$formatNumber($value, $picture, $options)<n-so?:s>Formats a number with an XPath picture string
$formatBase($value, $radix)<n-n?:s>Formats a number in another base (2 to 36)
$formatInteger($value, $picture)<n-s:s>Formats an integer with an XPath picture string (words, roman, letters, digits)
$parseInteger($value, $picture)<s-s:n>Parses an integer written according to an XPath picture string
$number($arg)<(nsb)-:n>Casts a value to a number
$floor($arg)<n-:n>Rounds down
$ceil($arg)<n-:n>Rounds up
$round($arg, $precision)<n-n?:n>Rounds half to even, optionally to a number of decimal places
$abs($arg)<n-:n>Absolute value
$sqrt($arg)<n-:n>Square root
$power($arg, $exp)<n-n:n>Raises a number to a power
$random()<:n>A pseudo-random number between 0 (inclusive) and 1 (exclusive)

Aggregation functions

Details and examples: Aggregation functions.

FunctionSignatureDescription
$sum($array)<a<n>:n>Sum of an array of numbers
$count($array)<a:n>Number of items in an array
$max($array)<a<n>:n>Largest number in an array
$min($array)<a<n>:n>Smallest number in an array
$average($array)<a<n>:n>Mean of an array of numbers

Boolean functions

Details and examples: Boolean functions.

FunctionSignatureDescription
$boolean($arg)<x-:b>The effective boolean value of a value
$not($arg)<x-:b>Logical negation of the effective boolean value
$exists($arg)<x:b>Whether a value is defined

Array functions

Details and examples: Array functions.

FunctionSignatureDescription
$zip()<a+>Combines arrays item by item into an array of arrays
$append($arg1, $arg2)<xx:a>Concatenates two values into an array
$reverse($arr)<a:a>Reverses an array
$sort($arr, $comparator)<af?:a>Sorts an array, optionally with a comparator function
$shuffle($arr)<a:a>Shuffles an array into a random order
$distinct($arr)<x:x>Removes duplicate values from an array

Object functions

Details and examples: Object functions.

FunctionSignatureDescription
$keys($arg)<x-:a<s>>The keys of an object, or the union of keys of an array of objects
$lookup($input, $key)<x-s:x>The value of a key in an object, or in each object of an array
$spread($arg)<x-:a<o>>Splits an object into an array of single-key objects
$merge($arg)<a<o>:o>Merges an array of objects into one; later keys win
$each($obj, $func)<o-f:a>Applies a function to each key/value pair of an object

Higher-order functions

Details and examples: Higher-order functions.

FunctionSignatureDescription
$map($arr, $func)<af>Applies a function to each item of an array
$filter($arr, $func)<af>The items of an array for which a predicate holds
$single($arr, $func)<af?>The only item of an array matching a predicate; an error otherwise
$reduce($sequence, $func, $init)<afj?:j>Folds an array into a single value with a function
$sift($arg, $func)<o-f?:o>The key/value pairs of an object for which a predicate holds

Date and time functions

Details and examples: Date and time functions.

FunctionSignatureDescription
$now($picture, $timezone)<s?s?:s>The evaluation’s timestamp as an ISO 8601 string, or formatted with a picture
$millis()<:n>The evaluation’s timestamp in milliseconds since the epoch
$fromMillis($millis, $picture, $timezone)<n-s?s?:s>Formats milliseconds since the epoch as a timestamp string
$toMillis($timestamp, $picture)<s-s?:n>Parses a timestamp string into milliseconds since the epoch

Encoding functions

Details and examples: Encoding functions.

FunctionSignatureDescription
$base64encode($str)<s-:s>Encodes a string as Base64 (each character taken as a byte)
$base64decode($str)<s-:s>Decodes a Base64 string (each byte becomes a character)
$encodeUrlComponent($str)<s-:s>Percent-encodes a URL component
$encodeUrl($str)<s-:s>Percent-encodes a URL, leaving reserved characters
$decodeUrlComponent($str)<s-:s>Decodes a percent-encoded URL component
$decodeUrl($str)<s-:s>Decodes a percent-encoded URL, leaving reserved characters encoded

Other functions

Details and examples: Other functions.

FunctionSignatureDescription
$error($message)<s?:x>Raises an error (D3137) with a message
$assert($condition, $message)<bs?:x>Raises an error (D3141) when a condition is false
$type($value)<x:s>The type of a value: null, number, string, boolean, array, object or function
$eval($expr, $focus)<sx?:x>Parses and evaluates a JSONata expression given as a string
$clone($arg)<(oa)-:o>A deep copy of a value

String functions

Most string functions use the context value when their first argument is omitted, so they work as path steps: Account.Order.OrderID.$uppercase(). Positions and lengths count characters (Unicode code points), except where noted.

$string

$string(arg, prettify?) converts a value to a string:

  • strings are returned unchanged;
  • functions become the empty string;
  • other values are written as JSON.

With prettify true, objects and arrays are indented. A number that is not finite is an error (D3001).

$string(5)
=> "5"
[1..3].$string()
=> ["1", "2", "3"]
$string({"a": [1, true, null]})
=> "{\"a\":[1,true,null]}"

Numbers are written with at most 15 significant digits, as in jsonata-js:

$string(0.1 + 0.2)
=> "0.3"

$length

$length(str) returns the number of characters in str.

$length("Hello World")
=> 11
$length("𝄞é")
=> 2

$substring

$substring(str, start, length?) returns the characters of str from position start (from 0), at most length of them. A negative start counts from the end.

$substring("Hello World", 3)
=> "lo World"
$substring("Hello World", 3, 5)
=> "lo Wo"
$substring("Hello World", -4, 2)
=> "or"

$substringBefore

$substringBefore(str, chars) returns the part of str before the first occurrence of chars, or all of str if chars does not occur.

$substringBefore("Hello World", " ")
=> "Hello"

$substringAfter

$substringAfter(str, chars) returns the part of str after the first occurrence of chars, or all of str if chars does not occur.

$substringAfter("Hello World", " ")
=> "World"

$uppercase

$uppercase(str) converts str to upper case.

$uppercase("Hello World")
=> "HELLO WORLD"

$lowercase

$lowercase(str) converts str to lower case.

$lowercase("Hello World")
=> "hello world"

$trim

$trim(str) normalizes whitespace in three steps:

  1. Tabs, carriage returns and line feeds become spaces.
  2. Runs of spaces become one space.
  3. Leading and trailing spaces are removed.
$trim("   Hello  \n World  ")
=> "Hello World"

$pad

$pad(str, width, char?) pads str to at least |width| characters with char (a space by default). A positive width pads on the right, a negative one on the left.

$pad("foo", 5)
=> "foo  "
$pad("foo", -5, "#")
=> "##foo"
$formatBase(35, 2) ~> $pad(-8, "0")
=> "00100011"

$contains

$contains(str, pattern) tests whether str contains pattern, which is either a string or a regular expression.

$contains("abracadabra", "bra")
=> true
$contains("Hello World", /wo/i)
=> true
input: address.json
Phone[$contains(number, /^077/)].type
=> "mobile"

$split

$split(str, separator, limit?) splits str into an array of strings around separator, which is a string or a regular expression. An empty string separator splits str into characters. limit caps the number of parts.

$split("so many words", " ")
=> ["so", "many", "words"]
$split("so many words", " ", 2)
=> ["so", "many"]
$split("too much, punctuation. hard; to read", /[ ,.;]+/)
=> ["too", "much", "punctuation", "hard", "to", "read"]

$join

$join(strings, separator?) joins an array of strings, with separator (empty by default) between them. Every item must be a string.

$join(["a", "b", "c"])
=> "abc"
$split("too much, punctuation. hard; to read", /[ ,.;]+/, 3) ~> $join(", ")
=> "too, much, punctuation"

$match

$match(str, pattern, limit?) returns the matches of a regular expression in str. Each match is an object with three fields:

  • match: the matched text;
  • index: its position;
  • groups: the texts captured by the parenthesized groups.

limit caps the number of matches. A single match is returned as a single object, following the sequence rules.

$match("ababbabbcc", /a(b+)/)
=> [
  {"match": "ab", "index": 0, "groups": ["b"]},
  {"match": "abb", "index": 2, "groups": ["bb"]},
  {"match": "abb", "index": 5, "groups": ["bb"]}
]
$match("ababbabbcc", /a(b+)/, 1).groups
=> ["b"]

$replace

$replace(str, pattern, replacement, limit?) replaces the occurrences of pattern (a string or a regular expression) in str. limit caps the number of replacements.

A string replacement with a regex pattern can refer to what was matched:

  • $0 is the whole match;
  • $1, $2, … are the captured groups (empty when there is no such group);
  • $$ is a literal $.

replacement can also be a function. It receives each match, as $match describes it, and returns the replacement string. When replacement is undefined, the occurrences are removed (see compatibility).

$replace("John Smith and John Jones", "John", "Mr")
=> "Mr Smith and Mr Jones"
$replace("John Smith and John Jones", "John", "Mr", 1)
=> "Mr Smith and John Jones"
$replace("John Smith", /(\w+)\s(\w+)/, "$2, $1")
=> "Smith, John"
$replace("265USD", /([0-9]+)USD/, "$$$1")
=> "$265"
(
  $celsius := function($m) { ($number($m.groups[0]) - 32) * 5 / 9 & "C" };
  $replace("temperature = 68F today", /(\d+)F/, $celsius)
)
=> "temperature = 20C today"

Adapted from the JSONata documentation (MIT license). The functions that format numbers as strings are on the numeric functions page.

Numeric functions

Numbers are 64-bit floats. A function whose result would not be a finite number fails with D3060 ($sqrt) or D3061 ($power).

$number

$number(arg) converts a value to a number:

ArgumentResult
a numberunchanged
a string in JSON number syntaxthat number
a string starting with 0x, 0o or 0ba hexadecimal, octal or binary integer
true, false1, 0
anything elseerror D3030
$number("5")
=> 5
$number("0x12")
=> 18
["1", "2.5", "1e3"].$number()
=> [1, 2.5, 1000]
$number("five")
=> error D3030

$abs

$abs(n) returns the absolute value of n.

$abs(-5)
=> 5

$floor

$floor(n) rounds n down to an integer.

[$floor(5.8), $floor(-5.3)]
=> [5, -6]

$ceil

$ceil(n) rounds n up to an integer.

[$ceil(5.3), $ceil(-5.3)]
=> [6, -5]

$round

$round(n, precision?) rounds n to precision decimal places (0 by default). A negative precision rounds to tens, hundreds, and so on. Halves round to the even neighbour (banker’s rounding), as in IEEE 754 and financial calculations.

[$round(123.456), $round(123.456, 2), $round(123.456, -1)]
=> [123, 123.46, 120]
[$round(11.5), $round(12.5), $round(125, -1)]
=> [12, 12, 120]

$power

$power(base, exponent) raises base to exponent.

[$power(2, 8), $power(2, -2), $power(2, 0.5)]
=> [256, 0.25, 1.4142135623730951]
$power(-1, 0.5)
=> error D3061

$sqrt

$sqrt(n) returns the square root of n, which must not be negative.

$sqrt(16)
=> 4

$random

$random() returns a pseudo-random number in [0, 1). It is not suitable for cryptography.

$random() < 1
=> true

$formatNumber

$formatNumber(n, picture, options?) formats a number with an XPath fn:format-number picture string:

Picture characterMeaning
0a mandatory digit
#an optional digit
.the decimal separator
,the grouping separator
%, ‰multiply by 100 or 1,000 and show the sign
ethe exponent separator (scientific notation)
;separates the picture for positive numbers from the one for negative numbers

options replaces the characters used, for example {"decimal-separator": ",", "grouping-separator": "."}. The other options are zero-digit, percent, per-mille, minus-sign, infinity, NaN, exponent-separator and pattern-separator.

$formatNumber(12345.6, "#,###.00")
=> "12,345.60"
$formatNumber(1234.5678, "00.000e0")
=> "12.346e2"
[$formatNumber(34.555, "#0.00;(#0.00)"), $formatNumber(-34.555, "#0.00;(#0.00)")]
=> ["34.56", "(34.56)"]
$formatNumber(0.14, "01%")
=> "14%"
$formatNumber(1234567.891, "#.##0,00", {"decimal-separator": ",", "grouping-separator": "."})
=> "1.234.567,89"

The number is formatted from the decimal with the fewest digits that converts back to it, as fn:format-number says, and those digits are rounded half to even: a long fraction shows no digits of the binary value, and the mantissa of an exponent picture stays below 10 to the number of its integer digits.

[$formatNumber(1.1, "0.00000000000000000000"), $formatNumber(9.99, "0.0e0"), $formatNumber(0.125, "0.00")]
=> ["1.10000000000000000000", "1.0e1", "0.12"]

$formatBase

$formatBase(n, radix?) writes the integer part of n in base radix, from 2 to 36 (10 by default).

[$formatBase(100, 2), $formatBase(2555, 16)]
=> ["1100100", "9fb"]

$formatInteger

$formatInteger(n, picture) writes an integer with an XPath fn:format-integer picture:

PictureOutput
0, 001, #,##0decimal digits, with a minimum width and grouping separators
w, W, Wwwords, in lower, upper or title case
i, IRoman numerals
a, Aletters: a…z, aa…
suffix ;oordinal: 1st, first
$formatInteger(2789, "w")
=> "two thousand, seven hundred and eighty-nine"
[$formatInteger(1999, "I"), $formatInteger(28, "A"), $formatInteger(3, "w;o")]
=> ["MCMXCIX", "AB", "third"]
$formatInteger(1234567, "#,##0")
=> "1,234,567"

$parseInteger

$parseInteger(str, picture) reads an integer written as $formatInteger writes it.

$parseInteger("twelve thousand, four hundred and seventy-six", "w")
=> 12476
$parseInteger("12,345,678", "#,##0")
=> 12345678

Adapted from the JSONata documentation (MIT license).

Aggregation functions

Aggregation functions reduce an array to a single value. A single value counts as an array of one item, and an empty array gives 0 for $sum and $count, and nothing for the others. The items of $sum, $max, $min and $average must be numbers (error T0412).

$sum

$sum(array) adds the numbers of array.

$sum([5, 1, 3, 7, 4])
=> 20
input: invoice.json
$sum(Account.Order.Product.Quantity)
=> 8

$count

$count(array) returns the number of items. It accepts any values.

[$count([1, 2, 3, 1]), $count("hello"), $count([])]
=> [4, 1, 0]
input: address.json
$count(Phone[type = 'office'])
=> 2

$max

$max(array) returns the largest number.

$max([5, 1, 3, 7, 4])
=> 7

$min

$min(array) returns the smallest number.

$min([5, 1, 3, 7, 4])
=> 1
$min([])
=> undefined

$average

$average(array) returns the mean of the numbers.

$average([5, 1, 3, 7, 4])
=> 4

Adapted from the JSONata documentation (MIT license).

Boolean functions

$boolean

$boolean(arg) converts a value to a Boolean. The same rules apply wherever JSONata needs a Boolean: in predicates, with and, or, ?: and in conditions.

ArgumentResult
a Booleanunchanged
a stringfalse if empty
a numberfalse if 0
nullfalse
an arraytrue if any item converts to true
an objectfalse if empty
a functionfalse
nothingnothing (false in conditions)
[$boolean("0"), $boolean(0), $boolean([0, ""]), $boolean([0, 1]), $boolean({})]
=> [true, false, false, true, false]

$not

$not(arg) converts arg to a Boolean and negates it.

[$not(true), $not(""), $not([1])]
=> [false, true, false]
input: library.json
library.books[$not("Kernighan" in authors)].title
=> ["Structure and Interpretation of Computer Programs", "Compilers: Principles, Techniques, and Tools"]

$exists

$exists(arg) returns true if arg produces a value, even null or false, and false if it produces nothing.

input: address.json
[$exists(Other.Misc), $exists(Other.Nothing), $exists(Phone[type = 'fax'])]
=> [true, false, false]

Adapted from the JSONata documentation (MIT license).

Array functions

A single value passed where an array is expected counts as an array of one item. Results that are arrays are proper arrays: they keep their structure even with one item.

$append

$append(array1, array2) returns the items of both arrays, in order. A value that is not an array is appended as one item.

$append([1, 2, 3], [4, 5, 6])
=> [1, 2, 3, 4, 5, 6]
$append("Hello", "World")
=> ["Hello", "World"]

$reverse

$reverse(array) returns the items in reverse order.

[1..5] ~> $reverse()
=> [5, 4, 3, 2, 1]

$sort

$sort(array, comparator?) returns the items in order. Without a comparator, the items must be all numbers or all strings (error D3070), and they sort in ascending order.

comparator($a, $b) returns true when $a must come after $b. The sort is stable: items the comparator considers equal keep their order.

$sort([5, 1, 3, 7, 4])
=> [1, 3, 4, 5, 7]
input: invoice.json
$sort(Account.Order.Product, function($l, $r) {
  $l.Description.Weight > $r.Description.Weight
}).`Product Name`
=> ["Trilby hat", "Bowler Hat", "Bowler Hat", "Cloak"]

For sorting by keys, the order-by stage ^(...) is shorter.

$distinct

$distinct(array) removes duplicates, keeping the first occurrence of each value. Values are compared as by =, deeply for arrays and objects.

$distinct([1, 2, 3, 3, 4, 3, 5])
=> [1, 2, 3, 4, 5]
input: invoice.json
$distinct(Account.Order.Product.Description.Colour)
=> ["Purple", "Orange", "Black"]

$shuffle

$shuffle(array) returns the items in random order.

$count($shuffle([1..9]))
=> 9

$zip

$zip(array1, array2, ...) groups the items at each position of its arguments into arrays. The result is as long as the shortest argument.

$zip([1, 2, 3], [4, 5, 6])
=> [[1, 4], [2, 5], [3, 6]]
$zip([1, 2, 3], [4, 5], [7, 8, 9])
=> [[1, 4, 7], [2, 5, 8]]

$count is described with the aggregation functions.


Adapted from the JSONata documentation (MIT license).

Object functions

Object fields keep the order in which they were inserted.

$keys

$keys(object) returns the field names of object. For an array of objects, it returns the names of all their fields, without duplicates.

input: address.json
$keys(Address)
=> ["Street", "City", "Postcode"]
input: address.json
$keys(Phone)
=> ["type", "number"]

$lookup

$lookup(object, key) returns the value of field key, for names that are not known in advance. For an array of objects, it returns the values from all of them.

input: address.json
$lookup(Address, "City")
=> "Winchester"
input: address.json
(
  $field := "number";
  $lookup(Phone[type = 'mobile'], $field)
)
=> "077 7700 1234"

$spread

$spread(object) splits an object into an array of objects with one field each. For an array of objects, it splits each of them.

input: address.json
$spread(Address)
=> [{"Street": "Hursley Park"}, {"City": "Winchester"}, {"Postcode": "SO21 2JN"}]

$merge

$merge(array) merges an array of objects into one. When several objects have the same field, the last one wins.

$merge([{"a": 1, "b": 2}, {"b": 3, "c": 4}])
=> {"a": 1, "b": 3, "c": 4}
input: address.json
$merge($spread(Address)[$keys($) != "Postcode"])
=> {"Street": "Hursley Park", "City": "Winchester"}

$each

$each(object, function) calls function($value, $key) for each field and returns the results.

input: address.json
$each(Address, function($v, $k) { $k & ": " & $v })
=> ["Street: Hursley Park", "City: Winchester", "Postcode: SO21 2JN"]

$sift, which keeps the fields that satisfy a function, is described with the higher-order functions.


Adapted from the JSONata documentation (MIT license).

Higher-order functions

These functions take a function as an argument. The function receives an item and, if it declares more parameters, the item’s position and the whole array (or, for $sift, the field name and the whole object).

$map

$map(array, function) returns the results of function($value, $index, $array) for each item. Results follow the sequence rules: one result is returned as itself, and none as nothing.

$map([1, 2, 3], function($v) { $v * 2 })
=> [2, 4, 6]
$map([1..5], $string)
=> ["1", "2", "3", "4", "5"]
input: address.json
$map(Email.address, function($v, $i, $a) { "Item " & ($i + 1) & " of " & $count($a) & ": " & $v })
=> [
  "Item 1 of 4: fred.smith@my-work.com",
  "Item 2 of 4: fsmith@my-work.com",
  "Item 3 of 4: freddy@my-social.com",
  "Item 4 of 4: frederic.smith@very-serious.com"
]

$filter

$filter(array, function) keeps the items for which function($value, $index, $array) is true.

input: invoice.json
$filter(Account.Order.Product, function($v, $i, $a) { $v.Price > $average($a.Price) }).`Product Name`
=> "Cloak"

$single

$single(array, function?) returns the only item for which function is true. More than one match is an error (D3138), and so is none (D3139). Without a function, the array must have exactly one item.

input: invoice.json
$single(Account.Order.Product, function($v) { $v.SKU = "0406654608" }).`Product Name`
=> "Bowler Hat"
input: invoice.json
$single(Account.Order.Product, function($v) { $v.Price > 30 })
=> error D3138

$reduce

$reduce(array, function, init?) folds the array into one value. It calls function($accumulator, $value, $index, $array) for each item, carrying the result to the next call. Without init, the first item is the initial accumulator.

$reduce([1..5], function($acc, $v) { $acc * $v })
=> 120
input: invoice.json
$reduce(Account.Order.Product, function($acc, $p) { $acc + $p.Quantity }, 0)
=> 8

$sift

$sift(object, function) keeps the fields of object for which function($value, $key, $object) is true. With one argument it applies to the context value.

input: invoice.json
(Account.Order.Product)[0].$sift(function($v, $k) { $k ~> /^Product/ })
=> {"Product Name": "Bowler Hat", "ProductID": 858383}
$sift({"a": 1, "b": null, "c": 0}, function($v) { $v != null })
=> {"a": 1, "c": 0}

$sort takes a comparison function too; see array functions.


Adapted from the JSONata documentation (MIT license).

Date and time functions

JSON has no date type, so timestamps are strings, usually in ISO 8601 format, or numbers of milliseconds since the Unix epoch (1970-01-01T00:00:00Z). These functions convert between the two, with picture strings for other formats. Dates and times describes the picture string syntax.

$now

$now(picture?, timezone?) returns the time the evaluation started, as an ISO 8601 string in UTC, or formatted as $fromMillis would format it. Every call in one evaluation returns the same time.

$now() = $now()
=> true
$now() ~> $contains(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/)
=> true

$millis

$millis() returns the time the evaluation started, in milliseconds since the epoch. Like $now(), it is the same throughout one evaluation.

$millis() = $toMillis($now())
=> true

$fromMillis

$fromMillis(millis, picture?, timezone?) formats a number of milliseconds as a timestamp. It uses ISO 8601 without a picture, and an XPath fn:format-dateTime picture string otherwise. timezone, written ±HHMM, shifts the time from UTC.

$fromMillis(1510067557121)
=> "2017-11-07T15:12:37.121Z"
$fromMillis(1510067557121, "[M01]/[D01]/[Y0001] [h#1]:[m01][P]")
=> "11/07/2017 3:12pm"
$fromMillis(1510067557121, "[H01]:[m01]:[s01] [z]", "-0500")
=> "10:12:37 GMT-05:00"
$fromMillis(1510067557121, "[FNn], [D1o] [MNn] [Y]")
=> "Tuesday, 7th November 2017"

$toMillis

$toMillis(timestamp, picture?) parses a timestamp into milliseconds since the epoch. Without a picture it expects ISO 8601. With one, it parses according to the picture. A timestamp that does not match fails with D3110.

$toMillis("2017-11-07T15:07:54.972Z")
=> 1510067274972
$toMillis("10/12/2018", "[D]/[M]/[Y]") ~> $fromMillis("[Y]-[M01]-[D01]")
=> "2018-12-10"

A date and time without a time zone is read as UTC. jsonata-js reads it in the machine’s local time zone, so its results depend on where it runs; see Compatibility.

differs: jsonata-js reads the time in the local time zone
$toMillis("2018-12-10T10:00:00")
=> 1544436000000

Adapted from the JSONata documentation (MIT license).

Encoding functions

$base64encode

$base64encode(str) encodes a string in base 64. Each character is taken as one byte, so the string must be in the Latin-1 range (\u0000 to ÿ). Encode other text with $encodeUrlComponent first, if needed.

$base64encode("myuser:mypass")
=> "bXl1c2VyOm15cGFzcw=="

$base64decode

$base64decode(str) decodes base 64 into a string, reading the bytes as UTF-8.

$base64decode("bXl1c2VyOm15cGFzcw==")
=> "myuser:mypass"

$encodeUrlComponent

$encodeUrlComponent(str) percent-encodes the UTF-8 bytes of every character that is not allowed in a URL component. It behaves like JavaScript’s encodeURIComponent.

$encodeUrlComponent("?x=test")
=> "%3Fx%3Dtest"

$encodeUrl

$encodeUrl(str) percent-encodes a whole URL, keeping the characters that have a meaning in URLs (:/?#[]@!$&'()*+,;=). It behaves like JavaScript’s encodeURI.

$encodeUrl("https://mozilla.org/?x=шеллы")
=> "https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"

$decodeUrlComponent

$decodeUrlComponent(str) reverses $encodeUrlComponent. Malformed escapes fail with D3140.

$decodeUrlComponent("%3Fx%3Dtest")
=> "?x=test"

$decodeUrl

$decodeUrl(str) reverses $encodeUrl.

$decodeUrl("https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B")
=> "https://mozilla.org/?x=шеллы"

Adapted from the JSONata documentation (MIT license).

Other functions

$type

$type(value) returns the type of value: "null", "number", "string", "boolean", "array", "object" or "function". It returns nothing for nothing.

[$type(1), $type("1"), $type(null), $type([]), $type({}), $type($type)]
=> ["number", "string", "null", "array", "object", "function"]
$type(missing)
=> undefined

$error

$error(message?) stops the evaluation with error D3137 and the given message.

bindings: {"limit": -1}
$limit >= 0 ? $limit : $error("The limit must not be negative")
=> error D3137

$assert

$assert(condition, message?) stops the evaluation with error D3141 and the message when condition is false. When it is true, it returns nothing.

input: address.json
($assert(Age >= 18, "Adults only"); FirstName)
=> "Fred"
input: address.json
($assert(Age >= 30, "Too young"); FirstName)
=> error D3141

$eval

$eval(expression, context?) parses and evaluates a JSONata expression given as a string. The context value is context if given, the current context otherwise. A syntax error in expression fails with D3120; an evaluation error, with D3121. A limit of the evaluation that expression reaches keeps its own code, located at the call of $eval: depth (D1011), timeout (D1012), size (U1001), cancellation (U1003) and steps (U1006).

$eval("[1, $string(2), 3]")
=> [1, "2", 3]
input: address.json
$eval("FirstName & ' ' & Surname")
=> "Fred Smith"
$eval("a + b", {"a": 1, "b": 2})
=> 3

$clone

$clone(value) returns a deep copy of an object or array. Transforms use it to copy their input.

$clone({"a": [1, {"b": 2}]})
=> {"a": [1, {"b": 2}]}

Adapted from the JSONata documentation (MIT license).

Error reference

Every error jlens reports carries a stable code. The codes and messages match those of jsonata-js, so code that handles JSONata errors works unchanged. In a message template, {{name}} is replaced with the JSON form of the error detail name, and {{{name}}} with its raw text.

Errors expose:

  • code();
  • message();
  • position(), a UTF-16 offset just past the offending token, as in jsonata-js;
  • span(), the byte range of the offending text;
  • details such as token() and value().

Static errors (S)

Raised while compiling an expression.

CodeMessage
S0101String literal must be terminated by a matching quote
S0102Number out of range: {{token}}
S0103Unsupported escape sequence: \{{token}}
S0104The escape sequence \u must be followed by 4 hex digits
S0105Quoted property name must be terminated with a backquote ()`
S0106Comment has no closing tag
S0107Template string must be terminated with {{value}}
S0108A } in template string text must be escaped as \}
S0201Syntax error: {{token}}
S0202Expected {{value}}, got {{token}}
S0203Expected {{value}} before end of expression
S0204Unknown operator: {{token}}
S0205Unexpected token: {{token}}
S0206Unknown expression type: {{token}}
S0207Unexpected end of expression
S0208Parameter {{value}} of function definition must be a variable name (start with $)
S0209A predicate cannot follow a grouping expression in a step
S0210Each step can only have one grouping expression
S0211The symbol {{token}} cannot be used as a unary operator
S0212The left side of := must be a variable name (start with $)
S0213The literal value {{value}} cannot be used as a step within a path expression
S0214The right side of {{token}} must be a variable name (start with $)
S0215A context variable binding must precede any predicates on a step
S0216A context variable binding must precede the 'order-by' clause on a step
S0217The object representing the 'parent' cannot be derived from this expression
S0301Empty regular expressions are not allowed
S0302No terminating / in regular expression
S0402Choice groups containing parameterized types are not supported
S0401Type parameters can only be applied to functions and arrays
S0500Attempted to evaluate an expression containing syntax error(s)

Type errors (T)

Raised while evaluating, when a value has the wrong type.

CodeMessage
T0410Argument {{index}} of function {{token}} does not match function signature
T0411Context value is not a compatible type with argument {{index}} of function {{token}}
T0412Argument {{index}} of function {{token}} must be an array of {{type}}
T1003Key in object structure must evaluate to a string; got: {{value}}
T1005Attempted to invoke a non-function. Did you mean ${{{token}}}?
T1006Attempted to invoke a non-function
T1007Attempted to partially apply a non-function. Did you mean ${{{token}}}?
T1008Attempted to partially apply a non-function
T1010The matcher function argument passed to function {{token}} does not return the correct object structure
T2001The left side of the {{token}} operator must evaluate to a number
T2002The right side of the {{token}} operator must evaluate to a number
T2003The left side of the range operator (..) must evaluate to an integer
T2004The right side of the range operator (..) must evaluate to an integer
T2006The right side of the function application operator ~> must be a function
T2007Type mismatch when comparing values {{value}} and {{value2}} in order-by clause
T2008The expressions within an order-by clause must evaluate to numeric or string values
T2009The values {{value}} and {{value2}} either side of operator {{token}} must be of the same data type
T2010The expressions either side of operator {{token}} must evaluate to numeric or string values
T2011The insert/update clause of the transform expression must evaluate to an object: {{value}}
T2012The delete clause of the transform expression must evaluate to a string or array of strings: {{value}}
T2013The transform expression clones the input object using the $clone() function. This has been overridden in the current scope by a non-function.

Dynamic errors (D)

Raised while evaluating, for other run-time problems.

CodeMessage
D1001Number out of range: {{value}}
D1002Cannot negate a non-numeric value: {{value}}
D1004Regular expression matches zero length string
D1009Multiple key definitions evaluate to same key: {{value}}
D1011Stack overflow. Check for non-terminating recursive function. Consider rewriting as tail-recursive
D1012Evaluation timeout after {{value}} milliseconds. Check for infinite loop
D1013Object property names starting with _jsonata_ are reserved for internal use: {{value}}
D1014The location in a transform expression can only match objects in the copy that is being transformed
D2005The left side of := must be a variable name (start with $)
D2014The size of the sequence allocated by the range operator (..) must not exceed 1e7. Attempted to allocate {{value}}.
D2015The maximum sequence length of {{value}} was exceeded.
D2016The size of the string requested by the $pad function must not exceed 1e7. Attempted to allocate {{value}}.
D3001Attempting to invoke string function on Infinity or NaN
D3010Second argument of replace function cannot be an empty string
D3011Fourth argument of replace function must evaluate to a positive number
D3012Attempted to replace a matched string with a non-string value
D3020Third argument of split function must evaluate to a positive number
D3030Unable to cast value to a number: {{value}}
D3040Third argument of match function must evaluate to a positive number
D3050The second argument of reduce function must be a function with at least two arguments
D3060The sqrt function cannot be applied to a negative number: {{value}}
D3061The power function has resulted in a value that cannot be represented as a JSON number: base={{value}}, exponent={{exp}}
D3070The single argument form of the sort function can only be applied to an array of strings or an array of numbers. Use the second argument to specify a comparison function
D3080The picture string must only contain a maximum of two sub-pictures
D3081The sub-picture must not contain more than one instance of the 'decimal-separator' character
D3082The sub-picture must not contain more than one instance of the 'percent' character
D3083The sub-picture must not contain more than one instance of the 'per-mille' character
D3084The sub-picture must not contain both a 'percent' and a 'per-mille' character
D3085The mantissa part of a sub-picture must contain at least one character that is either an 'optional digit character' or a member of the 'decimal digit family'
D3086The sub-picture must not contain a passive character that is preceded by an active character and that is followed by another active character
D3087The sub-picture must not contain a 'grouping-separator' character that appears adjacent to a 'decimal-separator' character
D3088The sub-picture must not contain a 'grouping-separator' at the end of the integer part
D3089The sub-picture must not contain two adjacent instances of the 'grouping-separator' character
D3090The integer part of the sub-picture must not contain a member of the 'decimal digit family' that is followed by an instance of the 'optional digit character'
D3091The fractional part of the sub-picture must not contain an instance of the 'optional digit character' that is followed by a member of the 'decimal digit family'
D3092A sub-picture that contains a 'percent' or 'per-mille' character must not contain a character treated as an 'exponent-separator'
D3093The exponent part of the sub-picture must comprise only of one or more characters that are members of the 'decimal digit family'
D3100The radix of the formatBase function must be between 2 and 36. It was given {{value}}
D3110The argument of the toMillis function must be an ISO 8601 formatted timestamp. Given {{value}}
D3120Syntax error in expression passed to function eval: {{value}}
D3121Dynamic error evaluating the expression passed to function eval: {{value}}
D3130Formatting or parsing an integer as a sequence starting with {{value}} is not supported by this implementation
D3131In a decimal digit pattern, all digits must be from the same decimal group
D3132Unknown component specifier {{value}} in date/time picture string
D3133The 'name' modifier can only be applied to months and days in the date/time picture string, not {{value}}
D3134The timezone integer format specifier cannot have more than four digits
D3135No matching closing bracket ']' in date/time picture string
D3136The date/time picture string is missing specifiers required to parse the timestamp
D3137{{{message}}}
D3138The $single() function expected exactly 1 matching result. Instead it matched more.
D3139The $single() function expected exactly 1 matching result. Instead it matched 0.
D3140Malformed URL passed to ${{{functionName}}}(): {{value}}
D3141{{{message}}}
D3142A width modifier in a date/time picture string cannot be greater than 100: {{value}}
D3150The timezone must be a number of hours and minutes, such as +0530: {{value}}

Guardrail errors (U)

Raised when an evaluation exceeds its configured limits, is cancelled, or needs what jlens does not support. U2001 is raised by jlens eval --json for an input document that is not valid JSON. The C API under the Java package raises U2001 for input that is not valid JSON, U2002 for a handle that is unknown or freed, U2003 for an expression that is not UTF-8, U2004 for an internal error, and U2005 for options, reads, a JSON Schema or a service’s declarations that are not in their form.

CodeMessage
U1001{{{message}}}
U1002The function ${{{token}}} returned a promise: asynchronous functions are not supported
U1003The evaluation was cancelled
U1004The input could not be read: {{{message}}}
U1005A function passed to ${{{token}}} was called after ${{{token}}} returned
U1006The evaluation exceeded its budget of {{value}} steps
U2001The input is not valid JSON: {{{message}}}
U2002The {{{token}}} handle {{value}} is unknown: it was never created, or it was freed
U2003The expression is not valid UTF-8: {{{message}}}
U2004Internal error in jlens, please report it: {{{message}}}
U2005Invalid {{{token}}}: {{{message}}}

Warnings (W)

jlens-specific. Warnings are reported as diagnostics by jlens check and parse_recover, and never stop evaluation.

CodeMessage
W0101This annotation is not attached to an expression and will be ignored
W0102Unknown annotation tag @{{{tag}}}; expected @label, @message or @id
W0103The value of annotation tag @{{{tag}}} should be a JSON string literal
W0201Field {{token}} is not in the schema{{{hint}}}
W0202Unknown function ${{{token}}}{{{hint}}}
W0203Function ${{{token}}} takes {{{expected}}} but is given {{{count}}}
W0204Variable ${{{token}}} is not declared{{{hint}}}
W0205Argument {{{index}}} of ${{{token}}} is {{{type}}}, which does not match the signature {{{signature}}}
W0206The value {{{value}}} is not one of the allowed values{{{hint}}}
W0207The {{{side}}} side of {{{token}}} is {{{type}}}, which has no order
W0208The sides of {{{token}}} are {{{lhs}}} and {{{rhs}}}, which cannot be compared
W0209The {{{side}}} side of {{{token}}} is {{{type}}}, not a number
W0210The value {{{value}}} never equals {{{type}}}
W0211The operand of - is {{{type}}}, not a number
W0212The result is {{{type}}}, never {{{expected}}}
W0213The result may be {{{type}}}, not {{{expected}}}
W0214The result may be undefined, not {{{expected}}}, because of {{{token}}}
W0215The {{{side}}} of {{{token}}} {{{reason}}}; {{{hint}}}

Audit annotations

An annotation attaches business metadata to part of an expression: a label, a message and an identifier. jlens uses annotations to make audit trees and explanations readable. Annotations are written as JSONata comments, so an annotated expression is still valid JSONata and evaluates identically in any other implementation.

/** @label "Authorized customer" @message "The customer login must be on the approved list." */
customer.login in $approved
and
/** @label "Minimum total" @id "RULE-042" */
$sum(items.(unitPrice * quantity)) > 50000

Syntax

An annotation is a block comment that starts with /**. The empty comment /**/ and ordinary /* ... */ comments are not annotations.

ElementMeaning
@label "…"Short name shown in audit trees and explanations
@message "…"Longer explanation of what the expression checks
@id "…"Stable identifier, for referring to this check from other systems
text before the first tagFree-form description

Tag values are JSON string literals, so \", \n and é escapes work. Leading * characters on continuation lines are ignored, so multi-line comments can be written JSDoc-style:

/**
 * Customers must be registered partners.
 * @label "Authorized customer"
 * @id "IMP-001"
 */
customer.login in $approved

When several annotations precede the same expression, they are merged and later tags win.

What an annotation covers

An annotation covers the operand that follows it. It extends to the right as far as the surrounding operators allow, but never past and or or, nor past operators that bind more loosely: ? (the conditional), := and ... In practice:

ExpressionAnnotated part
/** A */ x.y in $list and zx.y in $list
a and /** A */ b > 1 or cb > 1
/** A */ $total > 100 ? "big" : "small"$total > 100 (the condition)
a - /** A */ b + cb (the operand of -)
$f(/** A */ items.price, 2)items.price (the argument)
/** A */ (x or y)the whole parenthesised block
$x := /** A */ $sum(values)$sum(values) (the bound value)

Annotations never change how an expression is parsed. The syntax tree of an annotated expression is the same as the tree of the expression with its comments removed; only the annotation metadata is added to one node.

To label a whole and/or chain, wrap it in parentheses, as the rule in fixtures/shipping-rule.jsonata does:

/** @label "Order category check" */
(
  /** @label "Electronics group" */ ('electronic' in items.type and $electronics > $total * 0.3)
  or
  /** @label "Blue items group" */ ('blue' in items.color and $blueTax < $averageTax)
)

Warnings

Annotation problems are warnings: they are reported, but they never stop compilation or evaluation.

CodeWhen
W0101The annotation precedes something that is not an expression, such as an operator, a closing bracket, or the end of the input
W0102Unknown tag, such as @severity
W0103A tag value is not a quoted JSON string; the rest of the line is used as the value

Run jlens check to see them:

$ jlens check '/** @label "Total" @severity "high" */ $sum(items.price) > 100'
warning[W0102]: Unknown annotation tag @severity; expected @label, @message or @id
 --> <expr>:1:20
  |
1 | /** @label "Total" @severity "high" */ $sum(items.price) > 100
  |                    ^^^^^^^^^
<expr>: 0 error(s), 1 warning(s)

In the API

After parsing, the annotation is available on the annotated node as Node::annotation. It also appears in the JSON form of the syntax tree (jlens ast):

{ "type": "binary", "op": "in", "annotation": { "label": "Authorized customer", "span": { … } } }

The audit guide explains how annotations appear in audit trees.

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

Command-line interface

The jlens binary evaluates, checks, explains and inspects JSONata expressions.

jlens eval      <EXPR> | -f FILE  [-i INPUT | --no-input] [--ndjson] [--filter]
                [-b BINDINGS] [-c | -r | --json] [--timeout MS] [--max-depth N]
                [--max-steps N] [--max-string-length BYTES] [--max-array-length N] [--max-result-size BYTES]
                [--now TIME] [--seed N]
                [--explain | --audit json|text] [--audit-level decisions|full] [--trace-log FILE]
jlens check     <EXPR> | -f FILE...  [--json] [--deny-warnings] [--schema SCHEMA]
                [--config FILE] [--path FILE]
jlens reads     <EXPR> | -f FILE...  [--union]
jlens test      FILE...  [--json] [--timeout MS] [--max-steps N]
                [--max-string-length BYTES] [--max-array-length N] [--max-result-size BYTES]
jlens functions [NAME] [--json]
jlens errors    [CODE] [--json]
jlens schema infer    SAMPLES...  [--each] [--overrides FILE] [-o SCHEMA]
jlens schema complete <EXPR> | -f FILE  [--schema SCHEMA] [--cursor N] [--json]
jlens schema uses     <EXPR> | -f FILE  [--schema SCHEMA] [--config FILE] [--path FILE]
jlens schema changes  OLD NEW  [--json]
jlens ast       <EXPR> | -f FILE  [--tokens | --raw] [--recover]

Every command takes the expression either as an argument or from a file with -f. Prefer -f for anything longer than a one-liner. Shells interpret $, " and * differently, and Windows shells (cmd.exe, PowerShell) in particular make quoting expressions awkward. Glob patterns in jlens check -f, jlens reads -f, jlens test and jlens schema infer are expanded by jlens itself, so they work in every shell.

Exit codes

CodeMeaning
0Success. check may still have printed warnings (unless --deny-warnings)
1The expression has errors: a syntax error, an evaluation error, or (with --ndjson) at least one line that failed; test: at least one case failed
2Usage or I/O problem: unreadable file, invalid JSON input, an invalid case file, bad arguments, a terminal on standard input

A syntax error ends with code 1 every command that needs the whole expression: eval, check, reads, ast, jlens schema uses and jlens schema result. The two of jlens schema then print the error on standard error and nothing on standard output, as their JSON has no place for an error. jlens schema complete is the exception: it completes an unfinished expression, and ends with 0.

Writing to a closed pipe, as in jlens functions | head, ends quietly with code 0.

For scripts and agents

jlens keeps a contract with the programs that run it, recorded in ADR 0008:

  • Standard output is data: results, JSON from --json, catalogs. Standard error is for people: rendered diagnostics, summaries, usage errors. Never parse standard error.
  • Decide on the exit code (see the table above), not on whether anything was printed: an undefined result prints nothing and still exits with 0.
  • Match errors by code (S0202, T2001, D1012…), never by message. Codes are listed in the error reference.
  • The format never depends on the terminal. A command prints the same thing when an agent runs it and when a person copies it into a shell. Ask for machine output with a flag.
  • Pass the expression with -f FILE and the input with -i FILE or --no-input. This avoids shell quoting. An eval that would read its input from a terminal fails with code 2 instead of waiting.
  • Use eval --json to get every outcome, errors included, as one line of JSON on standard output (see below), and check --json for the diagnostics of every file as one JSON array.
  • Test the expressions you write with jlens test and a file of cases, and read the failures from test --json (see below).
  • Fix the clock and the seed with --now and --seed when a result depends on $now(), $millis(), $random() or $shuffle(), so that the same command prints the same bytes when it is run again.

jlens eval

Evaluates the expression against a JSON document and prints the result. The document comes from -i FILE, or from standard input. An undefined result prints nothing. When standard input is a terminal and neither -i nor --no-input is given, eval fails with exit code 2 instead of waiting for a document.

$ jlens eval -f fixtures/shipping-rule.jsonata -i fixtures/online-store-order.json
{
  "action": "FREE_SHIPPING",
  "code": "OK_200"
}
OptionEffect
-i, --input FILEThe input document (default: standard input)
--no-inputEvaluate without an input document ($ is undefined)
-b, --bindings FILEA JSON object whose fields are bound as variables: {"limit": 10} makes $limit available
-c, --compactOne line per result
-r, --raw-outputPrint strings without quotes, like jq -r
--jsonPrint a JSON envelope instead of the bare result (see below)
--timeout MSStop an evaluation that runs longer (error D1012)
--max-depth NStop an evaluation that nests deeper (error D1011); the default is 50,000
--max-steps NStop an evaluation after this many steps (error U1006): each node evaluated, each function called back and each 1,024 steps of a regular expression’s backtracking. Unlike --timeout, the same on every machine; --audit json reports the steps taken in header.steps
--max-string-length BYTESStop an evaluation that builds a longer string (error U1001); the default is 256 MiB
--max-array-length NStop an evaluation that builds an array of more items (error U1001); the default is 16,777,216
--max-result-size BYTESStop an evaluation whose result is larger as compact JSON, counting a value each time it appears (error U1001); the default is 256 MiB
--now TIMEThe time seen by $now() and $millis(): milliseconds since the epoch, or an ISO 8601 timestamp such as 2026-01-01T00:00:00Z
--seed NSeed $random() and $shuffle(): the same seed gives the same results

Results are printed the way JavaScript prints JSON, so they match jsonata-js output: 2^64 prints as 18446744073709552000 and 1e21 as 1e+21.

eval parses the input without the fields the expression does not read (what jlens reads prints), so a rule that reads a few fields of a large document skips the rest of it. The skipped fields are still checked as JSON syntax, but a number too large for a float, or a lone surrogate escape such as "\ud800", passes there. --filter parses a matching document again, whole, to print it; --explain, --audit and --trace-log show input values, and parse the input whole.

Machine output: --json

With --json, every outcome is one compact JSON object, the envelope, on one line of standard output. Nothing needs to be read from standard error.

OutcomeEnvelope
A result{"ok":true,"result":…}
An undefined result{"ok":true,"undefined":true}
An error{"ok":false,"error":{"code":…,"message":…,"token":…,"value":…,"position":…,"line":…,"column":…}}
$ jlens eval --json -i fixtures/online-store-order.json 'customer.name + 1'
{"ok":false,"error":{"code":"T2001","message":"The left side of the \"+\" operator must evaluate to a number","token":"+","value":"Acme Stores","position":15,"line":1,"column":1}}
  • Decide on ok, and match errors by code; message is for people and may change.
  • token and value are the error’s details, as jsonata-js gives them, and absent when the error has none: token is usually the operator, function or name involved, and value the value at fault, or the limit that was reached (U1006 gives the step budget). A value of null is the value null, not a missing one.
  • line and column (1-based, the column in characters) mark the start of the offending text in the expression, as the human report does. position is the jsonata-js position, a UTF-16 offset usually just past the offending token. The three are absent when the error has no location.
  • An input document that is not valid JSON gives an envelope with code U2001, and exit code 2 as without --json.
  • With --filter, a matching document is the result, and a document that does not match prints nothing.
  • With --ndjson, every envelope also carries line, the number of its input line, so that results and errors can be paired with their input. A line that is not valid JSON gives a U2001 envelope, and processing continues.
  • --json cannot be combined with -r, --explain or --audit.
  • Fields are only ever added to the envelope: ignore the ones you do not know.

Many documents: --ndjson

With --ndjson, the input has one JSON document per line, and the expression is evaluated for each one. Results are printed one per line, as they are produced, so arbitrarily large inputs stream through in constant memory.

  • Blank lines are skipped.
  • Lines that are not valid JSON, and evaluations that fail, are reported on standard error with their line number. Processing continues, and the exit code becomes 1.
  • With --json, each result and each error is an envelope that carries its line number, and nothing is written to standard error.
$ jlens eval --ndjson -i fixtures/orders.ndjson '$sum(items.(unitPrice * quantity))'
50000
300
60000
line 5: invalid JSON: expected ident at line 1 column 2
$ jlens eval --ndjson --json -i fixtures/orders.ndjson '$sum(items.(unitPrice * quantity))'
{"ok":true,"line":1,"result":50000}
{"ok":true,"line":2,"result":300}
{"ok":true,"line":4,"result":60000}
{"ok":false,"line":5,"error":{"code":"U2001","message":"The input is not valid JSON: expected ident at line 1 column 2"}}
{"ok":true,"line":6,"undefined":true}

Selecting documents: --filter

With --filter, jlens prints the input documents for which the expression is truthy, instead of the results. Truthiness follows $boolean: false, 0, "", null, empty arrays, empty objects and undefined are false. Combined with --ndjson, this works like a grep for JSON:

$ jlens eval --ndjson --filter -i fixtures/orders.ndjson \
    "customer.login in ['alice.walker99', 'bob.harrison42'] and \$sum(items.(unitPrice * quantity)) > 50000"
{"number":"SO-3","customer":{"login":"bob.harrison42"},"items":[{"type":"toy","unitPrice":60000,"quantity":1}]}

Explaining results

OptionEffect
--explainPrints an explanation of how the result was reached, instead of the result
--audit jsonPrints the full audit tree as JSON (--audit text is the same as --explain)
--audit-level fullRecords every evaluated node, not only decisions
--trace-log FILEWrites every evaluation event to FILE as JSON Lines; combines with the options above
$ jlens eval --no-input --explain '/** @label "Positive" */ 3 > 0 and /** @label "Small" */ 3 < 2'
result: false
✘ Small — 3 < 2 → false (3 < 2)

These options apply to a single document; they cannot be combined with --ndjson or --filter.

jlens check

Parses the expression with error recovery and reports every problem it finds. It warns about calls of functions that are neither built in nor bound in the expression (W0202, with a suggestion such as $summ → $sum), and about calls with a number of arguments the function’s signature does not accept (W0203) or an argument whose type it does not accept (W0205, as in $length(1234)). With --schema, it also reports field names that the schema does not have (see the schema guide), values outside a field’s declared enum or const (W0206), and checks the types of fields passed to functions and of the operands of operators (W0207–W0211, as in total > 1000 with total a string, and W0215 for an operand that may be several values, as in items.qty > 1). Each problem is shown in context:

$ jlens check 'Account.Order[0;].Product'
error[S0202]: Expected "]", got ";"
 --> <expr>:1:16
  |
1 | Account.Order[0;].Product
  |                ^
<expr>: 1 error(s), 0 warning(s)

-f takes several files, and glob patterns such as rules/*.jsonata. Each file is reported in turn, followed by a total. Errors make the exit code 1; warnings alone do not, unless --deny-warnings is given. An unreadable file, or a pattern that matches nothing, ends with exit code 2 before anything is checked.

With --json, the diagnostics of all the files are printed as one compact JSON array on standard output, which suits editors, CI scripts and agents. Each diagnostic has file (absent for an expression given as an argument), the 1-based line and column (counted in characters), then the severity, code, message and span, in byte offsets into the file:

$ jlens check --json 'a +'
[{"line":1,"column":4,"severity":"error","code":"S0207","message":"Unexpected end of expression","span":{"start":3,"end":3}}]

Configuration: jlens.json

check reads the same jlens.json as the language server, so that the command line and the editors report the same problems. It maps file patterns to a schema, the variables and the host functions the expressions are evaluated with: calls of declared host functions are checked like those of built-in ones, and, once variables are declared, references to undeclared ones get W0204. By default, check reads the jlens.json of the current directory, if there is one; --config names another file, whose patterns and paths are relative to its folder.

The configuration applies to files given with -f, by their path. An expression given as an argument matches no pattern, unless --path gives it the path of a file it would be saved as, which need not exist; that suits checking an expression before writing it:

jlens check --path rules/discount.jsonata '$rate(type) * unitPrice'

--schema replaces the schema that the configuration gives a file, and keeps its variables and functions. --result-type and --context-path replace its resultType and contextPath: --result-type boolean, or several types, --result-type number,null, warns about a result that may not have one of them, and --context-path 'items[]' checks each expression as the body of the steps of that path:

jlens check --schema order.schema.json --result-type number --context-path 'items[]' 'unitPrice * quantity'

A configuration that cannot be read, or whose schema cannot be, ends with exit code 2.

A schema whose $refs lead to other files is read with them, when they are at the same relative paths from the schema’s file; nothing is read from the network. A $ref that is not followed prints a warning: line on standard error and leaves its place unknown, so nothing is reported under it; the exit code does not change. So does a keyword the load does not read, such as $dynamicRef. One more warning: line names the tuples that say nothing of the items after them, whose items are checked only at a literal index inside the tuple. See A schema in several documents and the keywords jlens reads.

To validate a directory of rules in CI, warnings included:

jlens check --deny-warnings -f 'rules/*.jsonata'

jlens reads

Prints, as JSON on standard output, the fields an expression may read of its input and of each binding, without evaluating it (ADR 0016). An application can then fetch only those fields, or tell which rules depend on a field. A field maps to true when it is read whole, or to the fields read inside it; the items of an array share the entry of the array:

$ jlens reads "$sum(items[type = 'book'].(price * $rate))"
{
  "input": {
    "items": {
      "price": true,
      "type": true
    }
  },
  "bindings": {
    "rate": true
  }
}

The answer is an upper bound: the input and bindings cut down to it give the expression the same result, or the same error code. input is absent when the expression does not read its input, and "everyBinding": true means it may read any binding (as $eval can). The constructs the analysis cannot follow, such as * and **, read their value whole; the crate guide and the ADR give the details.

-f takes several files, and glob patterns. The result is then an object keyed by file, even for one file, and --union prints instead the union of the files’ results: what an input must keep for all of them. With discount.jsonata holding customer.tier = 'gold' ? $sum(items.price) * 0.1 : 0 and shipping.jsonata holding $sum(items.weight) > 10 ? 15 : 5:

$ jlens reads --union -f rules/discount.jsonata rules/shipping.jsonata
{
  "input": {
    "customer": {
      "tier": true
    },
    "items": {
      "price": true,
      "weight": true
    }
  },
  "bindings": {}
}

A syntax error is reported on standard error, as jlens check reports it, and makes the exit code 1; nothing is printed on standard output, even for the other files.

jlens test

Runs files of test cases. A case file is a JSON object that gives one expression, inline with expr or as the path of a file with file (relative to the case file), and the cases it is evaluated with:

{
  "file": "../rules/discount.jsonata",
  "bindings": {"discount": 0.1},
  "cases": [
    {"name": "ten percent off", "input": {"items": [{"price": 10}, {"price": 30}]}, "result": 36},
    {"name": "no items", "input": {}, "undefined": true},
    {"name": "text prices", "input": {"items": [{"price": "10"}]}, "error": "T0412"}
  ]
}

Each case has an optional name, the input document (absent for none; null is a document), its own bindings, which are added to those of the file and win over them, and exactly one expectation:

KeyThe case passes when
"result": VALUEthe result equals VALUE. Numbers compare by value (1 equals 1.0), and the keys of objects in any order
"undefined": truethe result is undefined
"error": "CODE"the evaluation, or the compilation, fails with this error code. Messages are not compared

The file may also fix the clock with now (milliseconds or an ISO 8601 timestamp, as eval --now) and the random numbers with seed. Unknown keys are errors, so that a misspelt expectation does not pass unnoticed.

jlens test takes several files, and glob patterns such as tests/*.json. It reports each failed case, with what was expected and what the expression gave, then a summary per file. Had the third case above expected T2001:

$ jlens test tests/discount.json
FAIL tests/discount.json case 3: text prices
  expected: error T2001
  actual:   error T0412: Argument 1 of function "sum" must be an array of "numbers"
tests/discount.json: 2 passed, 1 failed

A failed case makes the exit code 1. A case file that cannot be read, or is invalid, ends with exit code 2 before any case runs. --timeout stops each evaluation after a number of milliseconds (error D1012), --max-steps after a number of steps (error U1006), and --max-string-length, --max-array-length and --max-result-size cap the size of what it builds, as they do for eval (error U1001).

With --json, the outcome is one compact JSON object on standard output, with the number of cases that passed and failed, and the failures. Each failure has the file, the 1-based case number, the name if there is one, and what was expected and what is actual, both in the shape of the eval --json envelope:

$ jlens test --json tests/discount.json
{"passed":2,"failed":1,"failures":[{"file":"tests/discount.json","case":3,"name":"text prices","expected":{"ok":false,"error":{"code":"T2001"}},"actual":{"ok":false,"error":{"code":"T0412","message":"Argument 1 of function \"sum\" must be an array of \"numbers\"","token":"sum","value":"10","position":5,"line":1,"column":1}}}]}

jlens functions

Lists the built-in functions by category, with their parameters and a summary. Given a name (with or without $), it describes one function; --json prints the catalog as JSON.

$ jlens functions formatNumber
$formatNumber($value, $picture, $options)
  signature: <n-so?:s>
  category:  Numeric
  Formats a number with an XPath picture string

The function reference is generated from the same catalog.

jlens errors

Lists the error and warning codes by category, with their message templates. Given a code (in any case), it describes one; --json prints the catalog as JSON, each entry with its code, category (static, type, dynamic, guardrail or warning) and template.

$ jlens errors S0202
S0202
  category: Static errors (S)
  message:  Expected {{value}}, got {{token}}

The error reference is generated from the same catalog.

jlens schema

CommandPurpose
jlens schema infer SAMPLES… [--each] [--overrides FILE] [-o SCHEMA]Infer a JSON Schema from sample documents
jlens schema complete <EXPR> --schema SCHEMA [--cursor N] [--json]List completions at a cursor position, given in characters (default: the end)
jlens schema uses <EXPR> [--schema SCHEMA] [--config FILE] [--path FILE]Print what an expression uses of its schema, as JSON: what the schema says of each field it reads. The schema, the variables and the host functions are found as jlens check finds them; a call to a declared host function reads its arguments alone. An expression with a syntax error has no answer: the error is printed and the exit code is 1
jlens schema result <EXPR> [--schema SCHEMA] [--config FILE] [--path FILE] [--result-type TYPES] [--context-path PATH]Print what the typing knows of the expression’s result, as JSON: types (null where they are not known), and the spans, in byte offsets, of the operands that may make it undefined or a sequence; with an expected type, from --result-type or the configuration, check: always, never, maybe or unknown. An expression with a syntax error has no answer: the error is printed and the exit code is 1, as for jlens check. The resultType of the WebAssembly and Java packages answers with types that are not known instead
jlens schema changes OLD NEW [--json]Print what changed between two answers of jlens schema uses for one expression, that of the schema it was written against and that of a new version; no change, or {} with --json, when nothing did

All are described in the schema guide; the last two in What an expression uses of its schema.

jlens lsp

Runs the language server on standard input and output. Editors start it; it is configured by the jlens.json of each workspace folder. See the editors guide.

jlens ast

Prints the processed syntax tree as JSON. This is the tree the evaluator walks, with node ids, spans, stages and annotations. Flags show earlier stages of the pipeline:

FlagOutput
(none)Processed tree (Ast)
--rawRaw parse tree, before post-processing
--tokensToken stream, with spans
--recoverKeep going after syntax errors; print the partial tree, with diagnostics on standard error

jlens ast is mostly useful for understanding how an expression is read, for example which part an annotation covers. The parsing chapter explains the tree.

Rust crate

jlens-core is the JSONata engine. jlens-schema adds schema inference and the language service; see the schema guide. This chapter covers jlens-core. Its API reference is on docs.rs.

[dependencies]
jlens-core = "0.37"
serde_json = "1"

The snippets in this chapter come from crates/jlens-core/tests/guide.rs, which runs them as tests.

Compile once, evaluate many times

use jlens_core::{Bindings, Expression};
use serde_json::json;

let expr = Expression::compile("$sum(items[type = $kind].(price * qty))")?;
let order = json!({"items": [
    {"type": "book", "price": 12.5, "qty": 2},
    {"type": "pen", "price": 1.5, "qty": 10}
]});
let bindings = Bindings::new().var("kind", "book");
let total = expr.evaluate(Some(&order), &bindings)?;
assert_eq!(total, Some(json!(25)));

Expression::compile parses the expression and prepares it for evaluation. A compiled expression is immutable and cheap to clone. Keep it, and evaluate it as often as needed, from any thread (see Threads).

Documents and results are serde_json::Values. Object fields keep their order (jlens enables serde_json’s preserve_order). Variables come from Bindings: $kind above. Bindings can also be collected from (String, Value) pairs, such as the fields of a JSON object.

Undefined

JSONata distinguishes nothing (an empty sequence) from null. In the API, nothing is None, both for the input and for the result:

let expr = Expression::compile("customer.email")?;
// No input document: `None`. A result of `None`: the expression produced nothing.
assert_eq!(expr.evaluate(None, &Bindings::new())?, None);
assert_eq!(
    expr.evaluate(Some(&json!({"customer": {}})), &Bindings::new())?,
    None
);

Guardrails

Expressions can recurse and loop. Bound their cost with Options, especially for expressions that users write:

use jlens_core::Options;
use std::time::Duration;

let options = Options::new()
    .timeout(Duration::from_millis(100)) // D1012 when exceeded
    .max_depth(500); // D1011 when exceeded
let runaway = Expression::compile("($f := function($n) { $f($n + 1) }; $f(0))")?;
let err = runaway
    .evaluate_with(None, &Bindings::new(), &options)
    .unwrap_err();
assert_eq!(err.code(), "D1012");

// The same budget stops the same evaluation everywhere: U1006 when spent.
let loops = Expression::compile("$sum($map([1..100], function($i) { $i * 2 }))")?;
let err = loops
    .evaluate_with(None, &Bindings::new(), &options.clone().max_steps(400))
    .unwrap_err();
assert_eq!(err.code(), "U1006");

The default depth limit is 50,000 levels natively; the stack grows as needed. There is no default timeout. Expressions nested more than 1,000 levels deep (counting each operator of a chain such as 1 + 2 + 3) are rejected when compiled (U1001), and so is a value nested more than 1,000 levels of arrays and objects deep when it is returned, compared or serialized. A string longer than Options::max_string_length (256 MiB), an array longer than Options::max_array_length (16,777,216 items) or a result larger than Options::max_result_size (256 MiB of JSON text) stops the evaluation with U1001 instead of exhausting memory. See Guardrails.

A timeout reads the clock every 256 steps (defined below), so it costs almost nothing, and fires at most 256 steps late; a regular expression reads it at each of its checks. Being a clock, it lets the same evaluation pass on a fast machine and fail on a slow one. Options::max_steps is a budget that does not depend on the machine: each node evaluated is a step, and so is each function a built-in or a host function calls back, and each 1,024 steps of a regular expression’s backtracking. The same expression, input and options take the same steps everywhere, natively and in WebAssembly, with or without a tracer, and fail with U1006 once the budget is spent. The header of an audit reports the steps an evaluation took (steps), to set a budget from. The limit does not bound the work inside one step, which the size limits bound: a range, $sort without a function, $string. For the same outcome on every platform, set max_depth too, since its default differs in WebAssembly. See ADR 0018.

Cancellation

A CancelToken stops an evaluation from another thread, for example when the request that started it goes away. Clones of a token share one flag:

use jlens_core::CancelToken;
use std::{thread, time::Duration};

let token = CancelToken::new();
let options = Options::new().cancel_token(token.clone());
let forever = Expression::compile("($loop := function() { $loop() }; $loop())")?;
let worker = thread::spawn(move || forever.evaluate_with(None, &Bindings::new(), &options));
thread::sleep(Duration::from_millis(50));
token.cancel(); // from any thread that holds a clone
let err = worker.join().unwrap().unwrap_err();
assert_eq!(err.code(), "U1003");

The evaluation checks the token at every step and fails with U1003. A host function that is running finishes first. A cancelled token stays cancelled, so create one per job.

Reproducible results

$now() and $millis() read the system clock once per evaluation, and $random() and $shuffle() draw from a generator seeded from it. Fix both in Options to get the same result from the same expression, input and options, for tests or for replaying a decision:

let options = Options::new()
    .now(1_700_000_000_000) // $now(), $millis()
    .seed(42); // $random(), $shuffle()
let expr = Expression::compile("{'at': $now(), 'order': $shuffle([1, 2, 3, 4, 5])}")?;
let bindings = Bindings::new();
let first = expr.evaluate_with(None, &bindings, &options)?.unwrap();
assert_eq!(first["at"], json!("2023-11-14T22:13:20.000Z"));
// Same expression, input and options: the same result.
assert_eq!(expr.evaluate_with(None, &bindings, &options)?, Some(first));

A seed reproduces results with the same version of jlens, on any platform; it does not reproduce the numbers jsonata-js draws from Math.random().

Errors

Every error has a stable code: S0xxx for syntax errors, T for type errors, D for dynamic errors, U1001 for size limits and U1006 for the step limit. Match on the code, not on the message:

let err = Expression::compile("Account.Order[0;]").unwrap_err();
assert_eq!(err.code(), "S0202");
assert_eq!(err.message(), r#"Expected "]", got ";""#);
assert_eq!(err.position(), Some(16)); // UTF-16 offset, as in jsonata-js
let span = err.span().unwrap(); // byte range of the offending token
assert_eq!((span.start, span.end), (15, 16));
assert_eq!(err.token().as_deref(), Some(";"));

let expr = Expression::compile("name + 1").unwrap();
let err = expr
    .evaluate(Some(&json!({"name": "x"})), &Bindings::new())
    .unwrap_err();
assert_eq!(err.code(), "T2001");
assert_eq!(err.value(), Some(&json!("x")));
// `Display` gives the code, the message and the position.
assert_eq!(
    err.to_string(),
    r#"T2001: The left side of the "+" operator must evaluate to a number (at position 6)"#
);

position matches jsonata-js: a UTF-16 offset, usually just after the offending token. span is a byte range, for slicing the source in Rust. Errors serialize to JSON with their code, message and details.

Host functions

The application can provide its own functions, called from expressions like built-in ones. Bind a HostFunction with Bindings::function:

use jlens_core::{Error, HostFunction};

// `$shipping(weight, region?)`: the region defaults to the context value's `region`.
let shipping = HostFunction::with_signature("<ns?:n>", |args, call| {
    let weight = args[0].as_ref().and_then(|w| w.as_f64()).unwrap_or(0.0);
    let region = match &args[1] {
        Some(region) => region.clone(),
        None => call
            .input()
            .map_or(json!(null), |order| order["region"].clone()),
    };
    let rate = match region.as_str() {
        Some("north") => 1.5,
        Some("south") => 2.0,
        _ => return Err(Error::new("SHIP01").with("message", format!("No rate for {region}"))),
    };
    Ok(Some(json!(weight * rate)))
})?;
let bindings = Bindings::new().function("shipping", shipping);

let expr = Expression::compile("$shipping($sum(items.weight))")?;
let order = json!({"region": "south", "items": [{"weight": 2}, {"weight": 1.5}]});
assert_eq!(expr.evaluate(Some(&order), &bindings)?, Some(json!(7)));

let err = Expression::compile("$shipping(3, 'west')")?
    .evaluate(None, &bindings)
    .unwrap_err();
assert_eq!(err.code(), "SHIP01");
assert_eq!(err.message(), r#"No rate for "west""#);
assert_eq!(err.position(), Some(10)); // the call, as for built-in functions
  • Arguments and results are JSON. None stands for undefined. A function passed as an argument (such as a lambda) arrives as None; HostCall::function gives a handle to call it (below).
  • Signatures use the notation of the built-in functions. HostFunction::with_signature checks the arguments before each call, with the same errors (T0410, T0412). A parameter with - takes the context value when the argument is missing. HostFunction::new(arity, ...) skips the check and passes the arguments as given.
  • The arity tells higher-order functions how many arguments to pass: $map passes the index only to functions with two parameters or more. Partial application ($shipping(?, 'north')) uses it too.
  • The context value is available through HostCall::input, which converts it to JSON only when called.
  • Errors returned by the function stop the evaluation. Give them a code of your own and a message detail. Like other errors, they get the position and token of the call.
  • Bindings take precedence over built-in functions of the same name, as in jsonata-js. A name holds a value or a function: binding one replaces the other.

Host functions are Send + Sync, so bindings that hold them can be shared between threads. A host function runs to completion: a timeout is checked again only once it returns, or when it calls a function it received.

Functions as arguments

A host function can call a function it receives, such as a fallback or a step to retry. HostCall::function(i) gives a Callable for argument i when it is a function: a lambda, a built-in function, a partial application, a chain or another host function.

// `$rate(region, fallback)`: the rate from the application's table, or `fallback(region)`.
let rate = HostFunction::with_signature("<sf:n>", |args, call| {
    match args[0].as_ref().and_then(|r| r.as_str()) {
        Some("north") => Ok(Some(json!(1.5))),
        Some("south") => Ok(Some(json!(2))),
        _ => {
            let fallback = call.function(1).expect("the signature requires a function");
            fallback.call(&[args[0].clone()])
        }
    }
})?;
let bindings = Bindings::new().function("rate", rate);

let expr = Expression::compile("$rate(region, function($r) { $length($r) / 10 })")?;
let order = json!({"region": "west"});
assert_eq!(expr.evaluate(Some(&order), &bindings)?, Some(json!(0.4)));

// An error in the fallback comes back to the host function, which returns it here.
let err = Expression::compile("$rate('west', function($r) { $error('No rate for ' & $r) })")?
    .evaluate(None, &bindings)
    .unwrap_err();
assert_eq!(err.code(), "D3137");
assert_eq!(err.message(), "No rate for west");
  • The call is part of the evaluation, as when $map calls its function. The context value is null, and a lambda keeps the variables of its definition. The call counts as a level of depth, so a recursion through a host function ends with D1011; it checks the timeout and the cancellation token; its result is limited by max_result_size. An audit shows its steps under the host function’s call.
  • Arguments and the result are JSON, as for the host function itself. A sequence comes back as an array or a single value; a function crosses as None, in both directions.
  • Errors come back as Err, with their codes and positions. The host function can handle them, or return them, which ends the evaluation.
  • The handle borrows the call: it cannot be kept and called after the host function returns.

Many expressions, one document

Each evaluate call converts the parts of its input document that the expression reads into jlens’s internal representation, one level at a time: a path step reads its one field of an object, other operations the object’s whole level. An expression that reads most of a document of a few dozen kilobytes (a filter over every item, say) spends more on that conversion than on the rule. To evaluate several rules against the same document, convert it once into a Document:

use jlens_core::Document;

let rules = [
    ("minimum total", "$sum(items.(price * qty)) >= 20"),
    ("at most 50 items", "$sum(items.qty) <= 50"),
    ("no pens", "$not('pen' in items.type)"),
];
let compiled: Vec<_> = rules
    .iter()
    .map(|(name, source)| Ok((*name, Expression::compile(source)?)))
    .collect::<Result<_>>()?;

let order = Document::parse(
    r#"{"items": [{"type": "book", "price": 12.5, "qty": 2},
                  {"type": "pen", "price": 1.5, "qty": 10}]}"#,
)?;
let failed: Vec<&str> = compiled
    .iter()
    .filter(|(_, rule)| {
        let outcome = rule.evaluate_document(&order, &Bindings::new(), &Options::default());
        outcome.ok().flatten() != Some(json!(true))
    })
    .map(|(name, _)| *name)
    .collect();
assert_eq!(failed, ["no pens"]);

Document::parse reads JSON text straight into the internal representation, and Document::new converts a serde_json::Value. A Document is not Send: use it on the thread that created it. Performance has measurements.

Documents built from Rust values

An application that keeps its state in Rust types and evaluates a few expressions each time it changes needs no serde_json::Value in between: Document::from_serialize serializes any Serialize value straight into a document (ADR 0019). It builds the document that Document::new(&serde_json::to_value(&state)?) builds, in less than half the time, and fails where to_value fails (a map key that is not a string, number or boolean, say).

use serde::Serialize;

#[derive(Serialize)]
struct Task {
    name: String,
    priority: u32,
    open: bool,
}
#[derive(Serialize)]
struct Queue {
    tasks: Vec<Task>,
}

let target = Expression::compile("(tasks[open]^(priority))[0].name")?;
let mut queue = Queue {
    tasks: vec![
        Task {
            name: "write".into(),
            priority: 30,
            open: false,
        },
        Task {
            name: "review".into(),
            priority: 12,
            open: true,
        },
        Task {
            name: "ship".into(),
            priority: 40,
            open: true,
        },
    ],
};
for expected in ["review", "ship"] {
    // The state changes, the document is built again.
    let doc = Document::from_serialize(&queue)?;
    let name = target.evaluate_document(&doc, &Bindings::new(), &Options::default())?;
    assert_eq!(name, Some(json!(expected)));
    queue.tasks.retain(|task| task.name != expected);
}

An application that evaluates only once or twice per state can skip the document: a Source written over its types reads only the fields an expression reaches, and Expression::evaluate_source evaluates against it. For ten records of twenty fields, one expression takes 3.7 µs that way, against 19 µs for building the document and evaluating; by four expressions the two are close, and by ten the document is faster (Performance).

A variable of Bindings is a serde_json::Value, and each evaluation against a document converts what the expression reads of it (what an expression reads, analysed once for each expression): nothing of a variable it does not read, and all of one it uses whole. To bind a value that is already in a document (each record in turn, as $self), take its part with Document::pointer, a JSON Pointer as serde_json::Value::pointer reads it, and bind it with Expression::evaluate_document_with. The part shares the document’s values, so binding it costs nothing, and the evaluation leaves it as it was, transforms included:

let doc = Document::parse(
    r#"{"limit": 20, "tasks": [
        {"name": "write", "hours": 12},
        {"name": "review", "hours": 30}
    ]}"#,
)?;
let late = Expression::compile("$self.hours > limit")?;
let options = Options::default();
let mut flagged = Vec::new();
for i in 0..2 {
    // `$self` is the task itself, shared with the document, not a copy.
    let task = doc.pointer(&format!("/tasks/{i}")).unwrap();
    let result =
        late.evaluate_document_with(&doc, &[("self", &task)], &Bindings::new(), &options)?;
    if result == Some(json!(true)) {
        flagged.push(task.to_json()["name"].clone());
    }
}
assert_eq!(flagged, [json!("review")]);

For an expression that runs on its variables alone, Document::undefined() stands for no input, as None does in Expression::evaluate.

Other input representations

An input held in another representation than serde_json (another JSON library, a database row, a host language’s objects) can be read the same way, one level at a time, without being converted first. Implement input::Source for it, and evaluate with Expression::evaluate_source; implement its read_field too when the representation looks up one field for less than it reads a whole object, and its length and read_item when it reads one item of an array for less than the whole array. The documentation of the input module has an example. A level that the source fails to read stops the evaluation with U1004. The WebAssembly package reads JavaScript objects this way.

A result can be written into another representation the same way, without building a serde_json::Value first (ADR 0017). Implement output::Builder, and evaluate with Expression::evaluate_source_to or evaluate_document_to: they give the result to a closure, which writes it with the builder, within the size limit of a result. The documentation of the output module has an example.

The fields an expression reads

Expression::reads tells which fields of its input and of each binding an expression may read, without evaluating it (ADR 0016): an application can fetch only those from a database, or know which rules depend on a field. The answer is a Reads, a tree of field names for the input and for each binding; union combines the answers of several expressions.

// `$rate` looks up a tax rate; it never reads the context of its call.
let rate = HostFunction::new(1, |args, _call| {
    Ok(Some(json!(if args[0] == Some(json!("BR")) {
        0.2
    } else {
        0.1
    })))
})
.without_input();
let bindings = Bindings::new().function("rate", rate);

let rules = [
    "$sum(items.(price * qty)) * $rate(customer.country) < 100",
    "$count(items) <= 50",
];
let mut reads = None;
for source in rules {
    let rule = Expression::compile(source)?.reads_with(&bindings);
    reads = Some(match reads {
        None => rule,
        Some(all) => rule.union(&all),
    });
}
let reads = reads.expect("at least one rule");
assert_eq!(
    serde_json::to_value(reads.input())?,
    json!({"items": {"price": true, "qty": true}, "customer": {"country": true}})
);

// Fetch only those fields, or cut a document down to them.
let order = json!({
    "items": [{"sku": "B-12", "price": 12.5, "qty": 2}],
    "customer": {"name": "Ada", "country": "BR"}
});
let cut = reads.input().expect("the rules read the input").cut(&order);
assert_eq!(
    cut,
    json!({"items": [{"price": 12.5, "qty": 2}], "customer": {"country": "BR"}})
);

// Or parse JSON text skipping the fields no rule reads: one document serves every rule.
let text = order.to_string();
let doc = Document::parse_cut(&text, reads.input().expect("the rules read the input"))?;
assert_eq!(doc.to_json(), cut);
for source in rules {
    let rule = Expression::compile(source)?;
    let result = rule.evaluate_document(&doc, &bindings, &Options::default())?;
    assert_eq!(result, Some(json!(true)));
}
  • The answer is an upper bound. On its input and bindings cut by its reads (Read::cut), an expression gives the same result, or fails with the same error code. Where the analysis cannot follow a value, under * or **, in a constructed object or in the result, it reads the value whole (true in the JSON form).
  • A host function can read the context of its call through HostCall::input, so a call to one reads that context whole: the whole input, at the top of an expression. Mark a function that does not with HostFunction::without_input, and analyse with Expression::reads_with, given the bindings: a call to it then reads only its arguments, and HostCall::input gives None. A parameter with - in its signature still reads the context it may take.
  • Document::parse_cut parses JSON text cut by a Read, skipping the fields it leaves out: given the union of several rules’ reads, one document serves them all, and the parse takes less time the less the rules read (Performance).
  • A binding named after a built-in function shadows it during the evaluation, but the analysis takes the name as the built-in’s: such an application cannot cut its input by it.

Explaining results

evaluate_audited records an audit tree of the evaluation: comparisons and their operands, and/or short circuits, conditionals, bindings, filters, and the labels of annotations. explain summarizes it:

use jlens_core::audit::{AuditOptions, explain};

let rule = Expression::compile(
    r#"/** @label "Big order" @message "Orders must total at least 100." */
       $sum(items.(price * qty)) >= 100"#,
)?;
let order = json!({"items": [{"price": 12.5, "qty": 2}]});
let (result, audit) = rule.evaluate_audited(
    Some(&order),
    &Bindings::new(),
    &Options::default(),
    &AuditOptions::decisions(),
);
assert_eq!(result?, Some(json!(false)));
let explanation = explain(&audit);
assert_eq!(explanation.result, "false");
assert_eq!(
    explanation.lines[0].text,
    "Big order — $sum(items.(price * qty)) >= 100 → false (25 >= 100)"
);
// The whole tree serializes to JSON, to store it with the decision.
let stored = serde_json::to_string(&audit)?;
assert!(stored.contains(r#""label":"Big order""#));

The audit guide describes the tree, the levels and the bounds that keep audits of large documents small.

Custom tracers

Audits are built by a tracer, an implementation of the Tracer trait that receives evaluation events. Every method has a default that does nothing, so a tracer implements only what it needs:

use jlens_core::Node;
use jlens_core::audit::{Tracer, ValueRef};

/// Counts the comparisons an evaluation makes.
#[derive(Default)]
struct Comparisons(usize);

impl Tracer for Comparisons {
    fn operands(&mut self, _node: &Node, _lhs: ValueRef<'_>, _rhs: ValueRef<'_>) {
        self.0 += 1;
    }
}

let expr = Expression::compile("items[price > 10 and qty < 5]")?;
let mut counter = Comparisons::default();
expr.evaluate_traced(
    Some(&json!({"items": [{"price": 12, "qty": 1}, {"price": 5, "qty": 9}]})),
    &Bindings::new(),
    &Options::default(),
    &mut counter,
)?;
assert_eq!(counter.0, 3); // the second item fails `price > 10`, so `qty < 5` is skipped

jlens provides three tracers:

  • AuditCollector builds audit trees;
  • JsonlTracer writes every event as a line of JSON;
  • TracingTracer, with the tracing feature, emits tracing events.

Without a tracer, the evaluator runs its fast path, so tracing costs nothing when unused.

Tools for editors

parse_recover keeps going after syntax errors. The syntax tree is public, with node ids, spans and annotations:

use jlens_core::{NodeKind, Severity, parse_recover};

// Recovering parsing never fails: it returns a partial tree and every problem found.
let ast = parse_recover("Account.Order[0;].Product");
let errors: Vec<_> = ast
    .diagnostics
    .iter()
    .filter(|d| d.severity == Severity::Error)
    .map(|d| (d.code.as_str(), d.span.start))
    .collect();
assert_eq!(errors, [("S0202", 15)]);

// Walk the tree, for example to list the variables an expression uses (functions are
// variables too).
let ast = jlens_core::parse("$a + $b * $sum(items)")?;
let mut variables = Vec::new();
ast.root.walk(&mut |node| {
    if let NodeKind::Variable { name } = &node.kind {
        variables.push(name.clone());
    }
});
assert_eq!(variables, ["a", "b", "sum"]);

The function catalog describes every built-in function, for completion lists and documentation:

let catalog = jlens_core::function_catalog();
let substring = catalog.iter().find(|f| f.name == "substring").unwrap();
assert_eq!(substring.signature, "<s-nn?:s>");
assert_eq!(substring.params, ["str", "start", "length"]);

Spans, here and in jlens_schema, are byte offsets into the expression text. A browser editor counts UTF-16 code units, as does an error’s position. Built once per text, Offsets converts both ways; an offset inside a character maps to the start of that character:

use jlens_core::Offsets;

// Spans are byte offsets; a browser editor counts UTF-16 code units.
let text = "nome = 'José' and 🎉";
let offsets = Offsets::new(text);
let byte = text.find("and").unwrap();
assert_eq!((byte, offsets.to_utf16(byte)), (15, 14));
assert_eq!(offsets.to_byte(14), 15);
// An emoji is two UTF-16 units: the end of the text is unit 20, byte 23.
assert_eq!(
    (offsets.to_utf16(text.len()), offsets.to_byte(20)),
    (20, 23)
);

For completion, diagnostics and hover against a schema, use jlens_schema::LanguageService; see the schema guide.

Threads

Expression is Send + Sync. Share one compiled expression between threads, for example behind an Arc:

use std::sync::Arc;
use std::thread;

let expr = Arc::new(Expression::compile("$uppercase(name)")?);
let workers: Vec<_> = ["ann", "bob"]
    .into_iter()
    .map(|name| {
        let expr = Arc::clone(&expr);
        thread::spawn(move || expr.evaluate(Some(&json!({"name": name})), &Bindings::new()))
    })
    .collect();
for worker in workers {
    assert!(worker.join().unwrap()?.is_some());
}

Each evaluation is independent and single-threaded. Values created during an evaluation never leave it, except as the serde_json::Value result.

Features

FeatureEffect
tracingAdds audit::TracingTracer, which reports evaluations as tracing spans and events

The minimum supported Rust version is 1.88. jlens-core compiles to wasm32-unknown-unknown; the WebAssembly guide covers the browser package built on it.

WebAssembly (browser)

jlens-wasm compiles jlens to WebAssembly as an ES module for browsers. It covers what the Rust crates do:

  • evaluation;
  • audit trees and explanations;
  • schema inference;
  • the language service (completion, diagnostics, hover, signature help) for editors.

It also runs in Node.js 20+ and Deno, provided init is given the .wasm bytes. A classic script with the .wasm embedded serves a page opened from disk, and anything that cannot resolve the .wasm file.

import init, { Expression } from "jlens-wasm";

await init();

const expr = new Expression("$sum(items[type = $kind].(price * qty))");
expr.evaluate({ items: [{ type: "a", price: 2.5, qty: 4 }] }, { kind: "a" }); // 10

Building the package

rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version <the wasm-bindgen version in Cargo.lock> --locked
cargo xtask wasm            # release build into crates/jlens-wasm/pkg
cargo xtask wasm --dev      # unoptimized, with Rust panics reported on the console

cargo xtask wasm does five things:

  1. It compiles the crate with the wasm-release profile, which optimizes for size and speed (opt-level = "s"), with link-time optimization. It builds the cdylib alone (cargo rustc --crate-type cdylib), since Cargo leaves the profile’s lto out of a cargo build of a crate that is an rlib too.
  2. It generates the JavaScript glue and the TypeScript declarations with wasm-bindgen --target web.
  3. It runs wasm-opt -Os from binaryen: the installed one, or the npm package through npx. Without either, the module is about 45% larger.
  4. It writes jlens.global.js, the same package as one classic script.
  5. It writes package.json.

The wasm-bindgen CLI must be the exact version in Cargo.lock, and the task checks this.

FileContents
jlens.jsThe ES module
jlens.d.tsTypeScript declarations
jlens_bg.wasmThe WebAssembly module: about 1.7 MiB, 673 KiB gzipped
jlens.global.jsThe package as one classic script, the module embedded: about 2.4 MiB, 968 KiB gzipped
jlens.global.d.tsTypeScript declarations of its global, jlens
package.jsonnpm metadata: "type": "module", exports, types

A size budget for the gzipped module is enforced in xtask/src/wasm.rs.

Loading the module

Call init() once, and await it, before using anything else. By default it fetches jlens_bg.wasm from next to jlens.js:

<script type="module">
  import init, { Expression } from "./pkg/jlens.js";
  await init();
</script>

Bundlers that understand new URL(..., import.meta.url) handle this as is. Vite, webpack 5, Rollup and esbuild all do (esbuild with a loader for .wasm). Otherwise, pass the module’s URL or its bytes:

// Vite: get the URL of the asset.
import wasmUrl from "jlens-wasm/jlens_bg.wasm?url";
await init({ module_or_path: wasmUrl });

// Node.js or Deno: pass the bytes.
import { readFile } from "node:fs/promises";
await init({ module_or_path: await readFile(new URL("./pkg/jlens_bg.wasm", import.meta.url)) });

initSync({ module }) instantiates synchronously from bytes or a WebAssembly.Module. This is useful in workers.

One file: jlens.global.js

A page opened from disk, at a file:// address, can neither import a module nor fetch, so it cannot load jlens.js. jlens.global.js is the same package as one classic script, with jlens_bg.wasm embedded in base64. It sets one global, jlens, which holds the exports of jlens.js, with init for its default export. With no argument, init() and initSync() instantiate the embedded module:

<script src="jlens.global.js"></script>
<script>
  jlens.init().then(() => {
    const expr = new jlens.Expression("$sum(items.(price * qty))");
    console.log(expr.evaluate({ items: [{ price: 2.5, qty: 4 }] })); // 10
  });
</script>

It also serves what cannot resolve the .wasm file: a classic worker loads it with importScripts("jlens.global.js"), and a module, a module worker or a bundler with import "jlens-wasm/global", which runs the script and sets the global. In TypeScript, that import declares it too; a classic script references it with /// <reference types="jlens-wasm/global" />.

Its cost is size: the .wasm in base64 is a third larger, about 2.4 MiB, and 968 KiB gzipped against 673 KiB for jlens_bg.wasm, as base64 compresses less well (serving the module compares them). A page that loads it pays for the whole module even if it never calls init, and the npm package unpacks to 4.4 MB, of which the script takes 2.5 MB. Starting is no slower: in Node.js 22, reading the script and init() take about 19 ms, and the module with its bytes about 26 ms. jlens.js does not change, nor what importing it loads. Each loads a module of its own, so a page that loads both has two instances, with classes that do not mix.

cargo xtask wasm writes it from the module that wasm-bindgen generates, putting each of its JavaScript snippets in a function of its own. It changes only what it recognises in the output of the wasm-bindgen version in Cargo.lock, and the build fails on anything else. The Node.js and browser tests run the whole suite against it, and open a page from file:// that loads it with one <script>.

Serving the module

Content-Security-Policy

A Content-Security-Policy decides whether a page may compile WebAssembly, as it decides for eval. A page whose policy has a script-src directive, or only a default-src, needs 'wasm-unsafe-eval' in its script-src:

Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'

'wasm-unsafe-eval' allows compiling WebAssembly and nothing else: eval and new Function stay forbidden, and jlens uses neither. 'unsafe-eval' would allow the module too, but those as well. Without either, init() rejects with a WebAssembly.CompileError, from jlens.js and jlens.global.js alike. In Edge, as in the other Chromium browsers, it reads:

CompileError: WebAssembly.instantiateStreaming(): Compiling or instantiating WebAssembly module violates the following Content Security policy directive because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'".

and in Firefox call to WebAssembly.instantiateStreaming() blocked by CSP, with WebAssembly.instantiate() in both when it comes from jlens.global.js. The message names 'unsafe-eval', but 'wasm-unsafe-eval' is the narrower fix.

jlens.js also fetches jlens_bg.wasm, so the policy’s connect-src, or its default-src, must allow the module’s origin. Otherwise init() rejects with a TypeError before compiling anything: Failed to fetch in Edge, NetworkError when attempting to fetch resource. in Firefox. jlens.global.js fetches nothing.

These were tried with the policies above sent as headers, in Edge 158 and Firefox 160.

Size

What the page loadsSizegzipbrotli
jlens.js and jlens_bg.wasm42 KiB + 1.7 MiB9 + 673 KiB8 + 496 KiB
jlens.global.js2.4 MiB968 KiB686 KiB

The sizes of 0.37, brotli at its highest quality, 11. To serve the module small:

  • Compress jlens_bg.wasm with brotli, sent with Content-Encoding: br: a quarter smaller than with gzip. A server that compresses as it sends often uses a lower quality (at 5, the module is 571 KiB); compressing the file once when deploying, at quality 11, and serving that copy keeps the smaller size.
  • Send it with Content-Type: application/wasm. init() then compiles the module with WebAssembly.instantiateStreaming, while it downloads. With any other type, it warns on the console and compiles only once the whole module has arrived.
  • Load jlens.js with the .wasm beside it, not jlens.global.js, wherever the page can load a module. The module in base64 compresses worse, a third more with brotli, and it is decoded and compiled only once the whole script has arrived. jlens.global.js is for what cannot fetch the .wasm: a page opened from disk, a classic worker.

Evaluating expressions

const expr = new Expression(source);         // compile once (throws JlensError on syntax errors)
expr.evaluate(input, bindings, options);     // evaluate many times
expr.evaluateJson(jsonText, bindings);       // JSON text in, JSON text out
expr.free();                                 // release it (or let the garbage collector do so)
  • input can be any JSON-compatible value. undefined, or no argument, means there is no input document, so $ is undefined. Values are read as JSON.stringify reads them. As a result, Date objects become strings, and functions and undefined fields are dropped. See how the input is read.
  • bindings is an object of variables and functions: {limit: 10} makes $limit available, and a function becomes a host function.
  • options sets the limits (timeout, maxDepth, maxSteps, maxStringLength, maxArrayLength, maxResultSize), and the clock and seed that make an evaluation reproducible: now fixes $now() and $millis() (milliseconds since the epoch, a Date or an ISO 8601 timestamp), and seed fixes $random() and $shuffle(). The options are read from the object, unlike the input: each once, as a property, so a getter or an inherited option works, and toJSON is not called. undefined and null mean the default; a number must be finite, so NaN or Infinity throws a TypeError, as an invalid Date does.
  • The result is a plain value, or undefined when the expression evaluates to undefined. Numbers are the same as in jsonata-js. An object of the result is a JavaScript object, so its integer-like keys come first, as in jsonata-js. Inside the expression, an object it builds keeps its keys in insertion order, which $keys, $string, $each and $spread show, and so does the text evaluateJson returns (compatibility).

evaluateJson takes the input as JSON text and returns the result as JSON text. For large documents that you already have as text, such as a fetch response body, it avoids converting the document to JavaScript objects and back. While it parses, it skips the fields the expression does not read, checking them as JSON syntax only.

How the input is read

evaluate reads its input during the evaluation, one object or array at a time, when the expression first reaches it (ADR 0010). A path such as customer.name reads two small objects, however large the rest of the document is. An object or array of more than 16 values is read whole, with everything it holds, through JSON.stringify, which is faster than reading its values one by one. An index into an array, such as items[0] or items[$i], reads the items it picks alone, however long the array is.

Two consequences follow:

  • Errors appear when their part is read. A cycle, a BigInt, or a toJSON method that throws makes JSON.stringify throw. evaluate throws the same exception, but only when the expression reads the object or array that holds it: an expression that never reaches it succeeds.
  • The input must not change during the evaluation. A host function that modifies the input object can change what the rest of the evaluation reads. Copy the input first if a function must modify it.

evaluateJson converts the fields the expression reads first; evaluateWithAudit and Document convert their whole input first.

Reusing a document

evaluate reads the parts of the input that the expression reaches, on every call. For an expression that reads most of a document of a few dozen kilobytes, that costs hundreds of microseconds, often more than the evaluation itself. To evaluate several expressions against one document (a set of rules, say), convert it once:

import { Document } from "jlens-wasm";

const doc = new Document(input);              // or Document.fromJson(text)
const results = rules.map((rule) => rule.evaluateDocument(doc, bindings));
doc.free();

Evaluations never modify a document. Performance has measurements.

With explicit resource management, using expr = new Expression(...) frees the expression at the end of the block.

Host functions

JavaScript functions, in the bindings or registered on an expression, are called from the expression like built-in functions:

const expr = new Expression("$shipping($sum(items.weight), region)");
expr.evaluate(order, { shipping: (weight, region) => weight * rates[region] });

// As in jsonata-js: available to every evaluation, with an optional signature.
expr.registerFunction("shipping", (weight, region) => weight * rates[region], "<ns:n>");
  • Arguments and the result pass through JSON, like the input. undefined stands for undefined, and a function argument arrives as a JavaScript function that calls it (below).
  • A signature (registerFunction’s third argument) checks the arguments before each call, with the errors of the built-in functions (T0410, T0412). A parameter with - receives the context value when the argument is missing: <n-:n> makes price.$double() work.
  • this is undefined. Use a signature with - to receive the context value.
  • The function’s length tells higher-order functions how many arguments to pass: $map passes the index only to functions with two parameters or more.
  • An exception thrown by the function is rethrown by evaluate as is. Its position and token are set to the call when it has none. evaluateWithAudit reports it with its code, or its name, and its message.
  • Asynchronous functions are not supported. A function that returns a promise fails with U1002. Fetch what the expression needs before evaluating it.
  • Precedence: a function in the bindings replaces a registered function of the same name, and both replace a built-in function.

The Rust crate guide describes the same model.

Functions as arguments

A host function can call a JSONata function it receives, such as a fallback or a step to retry: a lambda, a built-in function, a partial application, a chain or another host function.

const retry = (step, times) => {
  for (let i = 1; ; i++) {
    try {
      return step(i);
    } catch (e) {
      if (i >= times) throw e;
    }
  }
};
new Expression("$retry(function($i) { $lookup(sku, $i) }, 3)").evaluate(order, { retry, lookup });
  • The call is part of the evaluation, as when $map calls its function. The context value is null, and a lambda keeps the variables of its definition. The call counts as a level of depth, so a recursion through a host function ends with D1011; it checks the timeout; its result is limited by maxResultSize.
  • It is synchronous: it returns the result, where jsonata-js returns a promise. Code written for jsonata-js with await step(i) keeps working.
  • Arguments and the result pass through JSON. A sequence comes back as an array or a single value; a JavaScript function among the arguments becomes undefined, and a function result comes back as undefined.
  • Its length is 0 and its arity property is the number of parameters, as in jsonata-js.
  • Errors are thrown as a JlensError with their codes, or as the exception a host function threw. The host function can catch them, or let them through, which ends the evaluation with that error.
  • It is valid until the host function returns. Called later, from a promise or a timer, it throws U1005.

Errors

Errors are Error objects named JlensError. They carry the JSONata error fields; every offset is in UTF-16 code units, like JavaScript string indexes:

try {
  new Expression("Account.Order[0;]");
} catch (err) {
  if (err.name !== "JlensError") throw err;
  err.code;      // "S0202"
  err.message;   // 'Expected "]", got ";"'
  err.position;  // 16: where it was detected, as in jsonata-js
  err.start;     // 15: the offending source range
  err.end;       // 16
  err.token;     // ";"
}

Evaluation errors carry value too, when there is one (for T2001, the value that is not a number). Invalid arguments, such as bindings that are not an object or malformed JSON for evaluateJson, throw a TypeError instead. The error reference lists every code.

The fields an expression reads

reads() tells which fields of its input and of each binding an expression may read, without evaluating it (ADR 0016): an application can fetch only those from a database, or know which rules depend on a field. unionReads combines the answers of several expressions.

const expr = new Expression("$sum(items[type = $kind].(price * quantity)) * $rate(country)");
expr.reads({ rate: (country) => rates[country] });
// {input: {country: true, items: {price: true, quantity: true, type: true}},
//  bindings: {kind: true, rate: true}}

unionReads([expr.reads({ rate }), new Expression("customer.name").reads()]);
// {input: {country: true, customer: {name: true}, items: {...}}, bindings: {...}}
  • The answer is an upper bound. true reads the value whole; an object reads only the fields it lists, of an object, or of each item of an array; an empty object needs the value but none of its fields, as $count does. On its input and bindings cut down that way, an expression gives the same result, or fails with the same error code. Where the analysis cannot follow a value, under * or **, in a constructed object or in the result, it reads the value whole.
  • Pass the bindings the expression will be evaluated with. A JavaScript function cannot read the context of its call (this is undefined), so a call to one in the bindings, or registered on the expression, reads only its arguments, and the context a - parameter may take. A call to a function the analysis does not know may read its context: the whole input, at the top of an expression.
  • everyBinding: true says the expression may read any binding whole, as $eval can: keep them all.
  • A binding named after a built-in function shadows it during the evaluation, but the analysis takes the name as the built-in’s: such an application cannot cut its input by it.

Document.fromJson(text, read) parses JSON text cut by a Read, the input of reads() or of unionReads(). It skips the fields the Read leaves out, which on a wide document is several times faster (Performance), and the document serves each expression that went into the union as the whole one would:

const rules = sources.map((source) => new Expression(source));
const { input } = unionReads(rules.map((rule) => rule.reads(bindings)));
const doc = Document.fromJson(text, input);
const results = rules.map((rule) => rule.evaluateDocument(doc, bindings));

The fields skipped are checked as JSON syntax only: a number too large for a float, which a full parse rejects, passes there.

Explaining results

evaluateWithAudit evaluates and records how the result was reached; see the audit guide. Evaluation errors are reported in the result, not thrown:

const expr = new Expression('/** @label "Big order" */ $sum(items.(price * qty)) > $limit');
const { result, error, audit, explanation, explanationText } = expr.evaluateWithAudit(
  { items: [{ price: 2.5, qty: 4 }, { price: 1, qty: 3 }] },
  { limit: 20 },
  { level: "decisions", limits: { maxNodes: 1000 } },
);
result;           // false
explanationText;  // 'result: false\n✘ Big order — $sum(items.(price * qty)) > $limit → false (13 > 20)'
audit.root;       // { kind: "binary", op: ">", label: "Big order", operands: [13, 20], outcome: "false", ... }

The options are those of evaluate, plus two more:

  • level is "off", "decisions" (the default) or "full".
  • limits sets the capture limits: maxItems, maxString, maxDepth, maxRejected, maxNodes and maxSource.

explanation.lines holds structured lines (depth, passed, text, message, node) for rendering in a user interface. Audit node spans are UTF-16 offsets, so a viewer can highlight a node’s source in the editor. The web editor example does this.

Tooling

parseRecover(source) never throws. It returns the partial syntax tree and every diagnostic:

parseRecover("Account.Order[0;].");
// { ast: {...}, diagnostics: [{ severity: "error", code: "S0202", message: ..., span: {start: 15, end: 16} }] }

expr.ast() returns the processed tree of a compiled expression, and functions() returns the catalog of built-in functions. Spans are UTF-16 offsets throughout.

Schemas

inferSchema(samples, overrides?) infers a JSON Schema 2020-12 from sample documents. The schema guide describes what it records and the overrides format:

const schema = inferSchema([doc1, doc2], {
  "items[].type": { description: "Product category", enum: ["apparel", "electronic", "toy"] },
  "items[].internalCode": { hidden: true },
});

The result is an ordinary JSON Schema object. Store it, edit it by hand, or pass it to LanguageService.

An override path the samples lack declares a new field, which is what a misspelt path does too. missingOverridePaths(samples, overrides) lists those paths, each with the existing path it most likely meant, so that an editor can warn about them:

missingOverridePaths([order], { "items.type": { enum: ["apparel"] }, "customer.vip": {} });
// [{ path: "customer.vip" }, { path: "items.type", suggestion: "items[].type" }]

The language service

const service = new LanguageService({ schema, variables: { limit: { type: "number" } } });

const text = "items[type = 'a'].p";
service.complete(text, text.length);
// { range: {start: 18, end: 19},
//   items: [{ label: "price", kind: "field", detail: "integer", documentation: "Examples: `1`", insertText: "price" }] }

service.diagnostics("customer.Login");
// [{ severity: "warning", code: "W0201", span: {start: 9, end: 14},
//    message: 'Field "Login" is not in the schema; did you mean `login`?' }]

service.hover("customer.login", 10);
// { range: {start: 9, end: 14}, contents: '`login`: string\n\nExamples: `"1"`' }

service.signatureHelp("$substring(name, ", 17);
// { name: "$substring", signature: "<s-nn?:s>", params: ["$str", "$start", "$length"], activeParam: 1, ... }

The constructor takes one object of options, each optional:

OptionWhat it gives
schemaThe JSON Schema of the input documents. Without one, functions and variables are still completed
variablesThe variables the expressions are evaluated with: its keys are their names, with or without $, and its values are schemas, or null when the shape is unknown
functionsThe host functions, as {name, signature, params, summary} objects. They are completed first, and hover and signature help show them
sourcesThe documents that the $refs of the schemas lead to, below
resultType, contextPathWhat the expressions are, below
new LanguageService({
  schema,
  functions: [
    { name: "shipping", signature: "<ns:n>", params: ["weight", "region"], summary: "Shipping cost" },
  ],
});

Create a new service when an option changes. Construction is cheap.

An option the constructor does not have throws a TypeError, a misspelt one included. So does a call in the form before 0.35, whose arguments were positional, the schema first: a schema is not taken for the options, and neither is a second argument.

Completion items are ranked best first, and insertText replaces range. Field names that are not plain identifiers come quoted with backquotes. kind is field, variable, function, keyword, operator or value: a value of the enumeration of the left-hand side of =, != or in, inserted as a JSONata literal. Inside a string literal, range covers the whole literal, quotes included, and only values are suggested; open the list after = and on a quote to offer them while typing. documentation and hover contents are Markdown.

A field with an open domain (x-jlens-domain, or domain in the overrides) takes values only the application can fetch. Where its values are completed, complete also returns a valueRequest; fetch the values, then write each with valueLiteral:

const schema = inferSchema([order], { "customer.login": { domain: "customers" } });
const service = new LanguageService({ schema });
const text = "customer.login = 'al";
const { range, items, valueRequest } = service.complete(text, text.length);
// valueRequest: { domain: "customers", path: "customer.login", prefix: "al",
//                 range: {start: 17, end: 20}, quote: "'", conditions: [], inArray: false,
//                 listed: [] }
const logins = await fetchCustomers(valueRequest.prefix);   // the application's own source
const options = logins.map((login) => valueLiteral(login, valueRequest.quote)); // "'alice'"

range is the same as the completions’ range, in UTF-16 units. valueLiteral(value, quote?) writes a string in quote (" by default) when it can, and other values as JSON.

conditions lists the fields fixed to literals beside the value, for a domain whose values depend on another one; inArray says whether the value is an element of in [...], where several may be inserted, and listed holds the literals already in that array, not to offer again (schema guide):

// A schema whose items[].categories[].subgroup has a domain
const text = "items[categories[group = 'Electronics' and subgroup in ['TVs', '";
const { valueRequest } = service.complete(text, text.length);
// valueRequest.conditions: [{ path: "items[].categories[].group", values: ["Electronics"] }]
// valueRequest.inArray: true
// valueRequest.listed: ["TVs"]

CodeMirror 6

CodeMirror positions are UTF-16 offsets, like jlens offsets, so no conversion is needed. examples/web-editor/jlens-codemirror.js in the repository is a self-contained module to copy. It provides highlighting, completion, linting, hover and signature help, and takes an asynchronous source for the values of open domains (jlensExtensions(getService, signatureElement, { values })). The core of it is:

autocompletion({
  override: [(context) => {
    const { range, items } = service.complete(context.state.doc.toString(), context.pos);
    return {
      from: range.start, to: range.end, filter: false,
      options: items.map((i) => ({ label: i.label, detail: i.detail, apply: i.insertText })),
    };
  }],
}),
linter((view) =>
  service.diagnostics(view.state.doc.toString()).map((d) => ({
    from: d.span.start, to: d.span.end, severity: d.severity, message: d.message,
  })),
),

Monaco

Monaco works with line and column positions; convert with the model:

monaco.languages.registerCompletionItemProvider("jsonata", {
  triggerCharacters: [".", "[", "$", "=", '"', "'"],
  provideCompletionItems(model, position) {
    const { range, items } = service.complete(model.getValue(), model.getOffsetAt(position));
    const start = model.getPositionAt(range.start);
    const end = model.getPositionAt(range.end);
    return {
      suggestions: items.map((i) => ({
        label: i.label,
        insertText: i.insertText,
        detail: i.detail,
        documentation: i.documentation && { value: i.documentation },
        kind: monaco.languages.CompletionItemKind.Field, // map i.kind as needed
        range: new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column),
      })),
    };
  },
});
// Diagnostics: monaco.editor.setModelMarkers(model, "jlens", ...) with the same conversion.

A schema in several documents

A $ref may lead to another document. jlens never fetches one: the application gives each document with its URI, as the sources of LanguageService (the schema guide):

const sources = {
  uri: "https://example.com/schemas/order.json",   // of the schema, when it has no $id
  documents: { "https://example.com/schemas/common.json": common },
};
const service = new LanguageService({ schema: order, sources });

const report = schemaReport(order, sources);
// { unresolved: [{ place: "https://example.com/schemas/order.json#/properties/carrier",
//                  reference: "carrier.json",
//                  uri: "https://example.com/schemas/carrier.json",
//                  document: "https://example.com/schemas/carrier.json" }] }
// {} when every $ref was followed; `unread` lists the keywords not read, as
// [{ place: "#/properties/code", keyword: "type" }] for a type that names no JSON type,
// and `openTuples` the tuples that any item may follow, as [{ place: "#/properties/point" }]

A $ref that is not followed does not fail the service: its place is unknown, and nothing is completed or warned about under it. schemaReport lists those $refs, each with the document to add to documents; an application that can fetch them does, and makes the service again. A keyword the load does not read leaves its place unknown too, and unread lists it (the schema guide lists the keywords). A tuple that says nothing of the items after it is read, and openTuples lists it: its items are checked only at a literal index inside it, which may be less than the schema’s author meant. The documents serve the schemas of the variables too; uri is that of the input’s schema alone. Both throw a TypeError for sources that are not in this form.

The type of the result, and the context

Two options of LanguageService say what the expressions are, besides what their schemas say: resultType, the type their result must have, and contextPath, the path whose items they are evaluated against, as the body of items.( … ) (the schema guide). They are those of jlens.json in an editor:

const conditions = new LanguageService({ schema, resultType: "boolean" });
conditions.diagnostics('$contains(customer.name, "VIP")');
// [{ severity: "warning", code: "W0214", span: {start: 10, end: 18},
//    message: "The result may be undefined, not a boolean, because of customer" }]

const lines = new LanguageService({ schema, resultType: ["number"], contextPath: "items[]" });
lines.diagnostics("%.customer.login & ': ' & code");   // W0212: a string, never a number

conditions.resultType('$contains(customer.name, "VIP")');
// { types: ["boolean"], undefined: {start: 10, end: 18}, sequence: null, check: "maybe" }

resultType is a type’s name or an array of them, and number accepts an integer. The method resultType gives what the typing knows of the result: the types it may have (null where they are not known, as without a schema or with a syntax error), and the spans, in UTF-16 units, of the operands that may make it undefined or several values. check compares it with the option: always, never, maybe or unknown, absent when the service expects no type. Options not in this form throw a TypeError.

What an expression uses of its schema

An application that stores expressions written against a schema that changes keeps, beside each one, what it uses of the schema, and compares it when a new version arrives (the schema guide describes both answers):

const expression = new Expression('$sum(items[type = "book"].price)');
const uses = new LanguageService({ schema }).uses(expression.reads());
// { input: { "$": { types: ["object"] },
//            "items": { types: ["array"], required: true },
//            "items[]": { types: ["object"] },
//            "items[].price": { whole: true, types: ["number"], required: false },
//            "items[].type": { whole: true, types: ["string"], enum: ["book", "toy"],
//                              closed: true, required: true } },
//   bindings: {} }
const kept = JSON.stringify(uses);

// Later, with the new version of the schema:
const changes = usesChanges(JSON.parse(kept), new LanguageService({ schema: newSchema }).uses(expression.reads()));
// { input: { changed: { "items[].price": { types: { old: ["number"], new: ["integer", "string"] } } } } }
// {} when nothing the expression uses changed

uses takes the fields the expression reads, so that the application chooses them: expression.reads(bindings) knows that the JavaScript functions of the bindings do not read their context, where reads() alone takes the input as read whole by a function it does not know. usesChanges needs no service and no schema. Both throw a TypeError for an argument that is not in the form reads() or uses() returns.

The fields of a schema

An editor that offers its own list of attributes, or an application that matches the fields of two versions of a schema, takes them from fields() rather than walking the schema (the schema guide says what each holds):

const service = new LanguageService({ schema: {
  type: "object",
  required: ["status"],
  properties: {
    status: { type: "string", title: "Status", enum: ["open", "closed"], "x-attribute-id": "A17" },
    lines: { type: "array", items: { type: "object", properties: {
      sku: { type: "string", "x-jlens-domain": "products" } } } },
    internal: { type: "string", "x-jlens-hidden": true },
  },
} });
service.fields();
// [ { path: "$", typeSummary: "object", types: ["object"] },
//   { path: "lines", typeSummary: "array<object>", types: ["array"], required: false },
//   { path: "lines[]", typeSummary: "object", types: ["object"] },
//   { path: "lines[].sku", typeSummary: "string", types: ["string"], required: false,
//     domain: "products" },
//   { path: "status", typeSummary: "string", types: ["string"], required: true, label: "Status",
//     enum: ["open", "closed"], closed: true, extensions: { "x-attribute-id": "A17" } } ]

Each path is written as uses writes it, and they come in its order; a hidden field is left out, with what is under it. extensions holds the field’s own x- keywords as written, which jlens does not read, such as a key the application gives each field.

Fields renamed by a new version

When a new version of a schema renames fields, rename() rewrites an expression written against the old one, given a table of paths, each old path to its new one (the schema guide says what it renames and why it may not be sure). A table built from the two versions’ fields(), matched by a key of the application’s in extensions, fits:

const key = (field) => field.extensions?.["x-attribute-id"];
const newPaths = new Map(after.fields().filter(key).map((field) => [key(field), field.path]));
const renames = Object.fromEntries(before.fields()
  .filter((field) => newPaths.has(key(field)))
  .map((field) => [field.path, newPaths.get(key(field))]));
before.rename("status = 'open' and $sum(lines.(qty * price)) > 100", renames);
// { text: "status = 'open' and $sum(items.(quantity * price)) > 100",
//   edits: [ { span: { start: 25, end: 30 }, text: "items" },
//            { span: { start: 32, end: 35 }, text: "quantity" } ],
//   unsure: [] }

Spans are in UTF-16 code units. unsure lists the places it leaves as written, each with its span, path and reason (whole, string, mixed or lost). A text that does not compile throws its error, and a table that is not one of renames a TypeError.

Limits and memory

LimitDefaultError
Evaluation depth (maxDepth)500D1011
Evaluation time (timeout, milliseconds)noneD1012
Evaluation steps (maxSteps)noneU1006
Length of a string built (maxStringLength, bytes of UTF-8)256 MiBU1001
Items of an array built (maxArrayLength)16,777,216U1001
Size of the result as JSON text (maxResultSize, bytes)256 MiBU1001
Expression nesting1,000 levelsU1001
Nesting of arrays and objects in a value that is returned, compared or serialized1,000 levelsU1001

The size of the result counts a value each time it appears, as the JSON text does, and also limits the arguments passed to a host function. Wasm evaluations are synchronous, so there is no cancellation: use timeout or maxSteps.

A timeout reads the clock, so the same evaluation can pass natively and fail in WebAssembly, which is slower, or pass on one machine and fail on another. maxSteps does not depend on the machine: each node evaluated is a step, and so is each function a built-in or a host function calls back, and each 1,024 steps of a regular expression’s backtracking. The same expression, input and options take the same steps in every browser, in Node.js and natively, and fail with U1006 once the budget is spent; the error’s value is the limit. The header of an audit reports the steps an evaluation took (audit.header.steps), to set a budget from. For the same outcome on every platform, set maxDepth too, since its default differs natively. See ADR 0018. In a browser, an evaluation can also run in a Web Worker, and terminating the worker stops it; the web editor does this.

The depth limit is lower than on native targets (50,000). WebAssembly runs on the JavaScript engine’s stack, which is about 1 MiB in V8, and deep recursion beyond it raises a JavaScript RangeError. Such an error, like any trap, leaves the module instance unusable. The defaults keep evaluations inside the engine’s stack, with headroom. Raise maxDepth only if you have measured what your target engines allow. The jlens errors themselves (JlensError, TypeError) never affect the instance.

How deep an evaluation fits depends on the shape of the recursion and on V8’s compiler. V8 first runs the module with its baseline compiler (Liftoff), then recompiles the functions an evaluation uses often with its optimizing compiler (TurboFan), whose frames for jlens’s evaluator are about 1.6 times larger. Measured in Node.js 24 once the module is optimized, an audited recursion overflows V8’s stack near these depths (an unaudited one fits 25 to 45% more):

The recursive function’s bodyOverflows near
[$n, $n]^($f($n - 1)) (order-by)660
{'a': 1} ~> |$|{'b': $f($n - 1)}| (transform)680
{'a': $f($n - 1)}, [$n]{'k': $f($n - 1)} (group)720
[$n][$f($n - 1)] (filter)790
$f($n - 1) + 1, [$f($n - 1)]850
$n = 0 ? 0 : 1 + $f($n - 1)930

The default of 500 leaves room for shapes not measured here, and for engines with smaller stacks. The evaluator chapter has the details.

Expression, Document and LanguageService objects live in WebAssembly memory. The garbage collector frees them through FinalizationRegistry. Call free(), or use using, to release them promptly in loops.

TypeScript

The package ships jlens.d.ts. Every argument and result is typed: AuditResult, AuditTree, AuditNode, Explanation, Diagnostic, Completions, CompletionItem, ValueRequest, ValueCondition, Hover, SignatureHelp, FunctionInfo, JsonSchema, SchemaOverride, EvaluateOptions, AuditOptions and JlensError. Results of evaluate are unknown; narrow them as usual.

The web editor example

examples/web-editor is a complete page with no build step, published with this book as the web editor:

  • a JSONata editor (CodeMirror 6) with completion, diagnostics, hover and signature help, driven by a schema inferred from the input document;
  • a panel of schema overrides, passed to inferSchema with the input document, so that the structure still follows the document and the overrides add labels, descriptions, hidden fields and domains; the “Free shipping” example has some;
  • live evaluation, in a Web Worker (worker.js), so that a slow expression never blocks typing;
  • the explanation and an audit tree viewer; clicking a node selects its source;
  • the inferred schema;
  • ready-made examples, including the samples of try.jsonata.org;
  • a host function, $try (host-functions.js), that calls the function it receives, with an example that uses it: the worker registers it on each expression, and the page declares it to the language service;
  • a stand-in asynchronous source for open domains (domains.js), which answers after a short delay, as a server would: the “Open domains” example shows it on three fields, and in the “Free shipping” example, customer.login = ' completes the logins of its domain customers.
cargo xtask wasm
cargo xtask serve        # then open the printed /examples/web-editor/ address

CodeMirror is loaded from esm.sh through an import map, so the page needs network access. The page imports the package by its name, jlens-wasm, which the same import map resolves. cargo xtask site builds the published site in target/site, the book with the editor in editor/, and cargo xtask serve --site serves it.

Testing

cargo xtask wasm-test builds the package, then runs crates/jlens-wasm/tests/suite.mjs twice:

  • in Node.js;
  • in a headless Chrome, Chromium or Edge (set JLENS_BROWSER to choose the executable).

--require-browser fails when no browser is found, instead of skipping. --example also checks that the web editor loads and evaluates its sample, from the repository and as the site serves it.

Python

The Python package jlens runs the jlens engine in CPython, through native extension modules built with PyO3 (ADR 0014). It covers evaluation, host functions written in Python, and audit trees with their explanations. Its API is the one of the WebAssembly package, in Python’s style: snake_case names, keyword options, a timeout in seconds, and offsets counted in code points.

pip install jlens

The package is in beta until jlens 1.0: its API may still change in a minor release, as the changelog will say. The installation page lists the platforms it has wheels for.

The snippets in this chapter come from the scripts in crates/jlens-python/tests/guide/, which the package’s tests run.

Compile once, evaluate many times

from jlens import Expression

expr = Expression("$sum(items[type = $kind].(price * qty))")
order = {
    "items": [
        {"type": "book", "price": 12.5, "qty": 2},
        {"type": "pen", "price": 1.5, "qty": 10},
    ]
}
assert expr.evaluate(order, {"kind": "book"}) == 25

An Expression is compiled once and evaluated any number of times, from any thread. Compiling raises a JlensError on syntax errors.

expr = Expression(source)                       # compile once
expr.evaluate(input, bindings, **options)        # Python values in, Python values out
expr.evaluate_json(text, bindings, **options)    # JSON text in, JSON text out
expr.evaluate_document(document, bindings, **options)
expr.source                                      # the source text
  • input is the input document: dict, list, tuple, str, int, float, bool or None, nested in any way. None, or no argument, means there is no input document, so $ is undefined. See how the input is read.
  • bindings is a dict of variables and functions: {"limit": 10} makes $limit available, and a callable becomes a host function.
  • options are keyword arguments: the limits and the clock and seed that make an evaluation reproducible.
  • The result is a plain Python value: dict, list, str, int, float, bool or None. A number that is integral and below 1021 in magnitude becomes an int, as json.loads would read it from jsonata-js’s output; other numbers become a float.

Undefined and null

JSONata tells an undefined result (the expression produced nothing) from null. evaluate returns None for both:

from jlens import Expression

expr = Expression("customer.email")
assert expr.evaluate({"customer": {}}) is None  # undefined
assert expr.evaluate({"customer": {"email": None}}) is None  # null
# To tell them apart, ask in the expression:
assert Expression("$exists(customer.email)").evaluate({"customer": {}}) is False

evaluate_json keeps them apart: it returns None for an undefined result, and the text "null" for null.

Options

from jlens import Expression, JlensError

clock = Expression("[$now(), $random()]")
first = clock.evaluate(now="2024-01-02T03:04:05Z", seed=7)
assert first[0] == "2024-01-02T03:04:05.000Z"
assert clock.evaluate(now="2024-01-02T03:04:05Z", seed=7) == first

loop = Expression("($f := function($n) { $f($n + 1) }; $f(0))")
try:
    loop.evaluate(timeout=0.05)  # seconds
except JlensError as error:
    assert error.code == "D1012"

nested = Expression("$sum($map([1..1000], function($i) { $i }))")
try:
    nested.evaluate(max_steps=1000)  # the same on every machine
except JlensError as error:
    assert (error.code, error.value) == ("U1006", 1000)
  • timeout (seconds, a float) stops the evaluation with D1012.
  • max_steps (an int) stops it with U1006 once it has taken that many steps, the same on every machine; see limits.
  • max_depth, max_string_length, max_array_length and max_result_size bound the evaluation; see limits.
  • now fixes $now() and $millis(): milliseconds since the epoch, a datetime, or an ISO 8601 timestamp. A datetime without a time zone is local time, as its timestamp() reads it.
  • seed (an int) fixes $random() and $shuffle().

An unknown option raises a TypeError, and a value out of range a ValueError.

How the input is read

evaluate reads its input during the evaluation, one dict or list at a time, when the expression first reaches it, as the WebAssembly package does (ADR 0010). A path such as customer.name reads two small dictionaries, however large the rest of the document is.

PythonJSONata
dict and its subclasses, with str keysobject, in the order of the keys
list, tuplearray
str and its subclassesstring
int, float and their subclasses (an IntEnum, say)number; NaN and the infinities become null, as in JSON; an int beyond 253 the nearest number, as in jsonata-js; a subclass is read by its value, without calling its own methods (__float__)
boolboolean
Nonenull

Anything else, such as a set, a date, a key that is not a str, or a cycle, has no JSON form. Two consequences follow from reading the input as the expression goes:

  • Errors appear when their part is read. A value that cannot be read stops the evaluation with U1004, with the message json.dumps would give, when the expression reads it. A path step reads one field of a dictionary, and an index (items[0], items[$i]) the items of a list it picks; other operations (*, $keys, returning the dictionary) read the whole dictionary or list, and a key that is not a str fails then. An expression that never reaches the value succeeds (below).
  • The input must not change during the evaluation. A host function, or another thread, that modifies the input can change what the rest of the evaluation reads. In free-threaded Python, that gives a result mixing both states, or U1004, never a crash. Copy the input first if something must modify it.
from jlens import Expression, JlensError

order = {"customer": {"name": "Acme"}, "log": {"seen": {1, 2}}}  # a set is not JSON
assert Expression("customer.name").evaluate(order) == "Acme"  # `log` is never read
try:
    Expression("log.seen").evaluate(order)
except JlensError as error:
    assert error.code == "U1004"

Evaluations never modify their input. A lone surrogate in a str, which UTF-8 cannot hold, becomes U+FFFD.

JSON text

evaluate_json takes the input as JSON text and returns the result as JSON text. For a document you already have as text, such as an HTTP response body, it avoids building Python objects only to read them. While it parses, it skips the fields the expression does not read, checking them as JSON syntax only:

from jlens import Expression

expr = Expression("items.sku")
assert expr.evaluate_json('{"items": [{"sku": "A1"}, {"sku": "B2"}]}') == '["A1","B2"]'
assert expr.evaluate_json("{}") is None  # undefined

Invalid JSON raises a ValueError.

Reusing a document

evaluate reads the parts of the input that the expression reaches, on every call. To evaluate several expressions against one document (a set of rules, say), or one expression several times, convert the document once:

from jlens import Document

rules = [Expression("$count(items) > 1"), Expression("$sum(items.(price * qty)) > 25")]
document = Document(order)  # or Document.from_json(text)
assert [rule.evaluate_document(document) for rule in rules] == [True, True]

Building a Document converts the whole value at once, with the rules above, and raises a ValueError or a TypeError for what it cannot convert. Evaluations never modify a document.

Threads

Expression and Document objects can be shared between threads. evaluate_json and evaluate_document let other Python threads run while they evaluate: they release the GIL, and attach again only to call a host function written in Python. evaluate reads Python objects as it goes, so it holds the GIL throughout.

from concurrent.futures import ThreadPoolExecutor

from jlens import Document, Expression

expr = Expression("$sum(items)")
documents = [Document.from_json(f'{{"items": [{i}, {i}]}}') for i in range(100)]
with ThreadPoolExecutor(8) as pool:
    totals = list(pool.map(expr.evaluate_document, documents))
assert totals[:3] == [0, 2, 4]

The package supports free-threaded Python (3.14t and later), where the threads of a pool evaluate in parallel. A Document used by several threads is converted once more on each thread, the first time that thread evaluates against it.

On Linux distributions built on musl, such as Alpine, give threads a larger stack before you create them, if they evaluate expressions that call Python code, such as a host function:

threading.stack_size(8 << 20)  # 8 MiB, the default with glibc
with ThreadPoolExecutor(4) as pool:
    taxes = list(pool.map(lambda p: expr.evaluate({"price": p}), [8, 12]))

musl starts threads with a 128 KiB stack, so jlens evaluates on a larger stack of its own. CPython 3.14 and later cannot ask musl where a thread’s stack ends: they assume it is 4 MB long. When the stack jlens allocated happens to lie at that assumed end, the Python code called from it raises RecursionError or aborts the process (Unrecoverable stack overflow). This is rare, depends on where memory is mapped, and does not affect the main thread, whose stack is larger. With a stack larger than 4 MB, a thread evaluates on its own stack.

Host functions

Python callables, in the bindings or registered on an expression, are called from the expression like built-in functions:

def shipping(weight, region):
    return weight * rates[region]


expr = Expression("$shipping($sum(items.weight), region)")
assert expr.evaluate(order, {"shipping": shipping}) == 10

# As in jsonata-js: available to every evaluation, with an optional signature.
expr.register_function("shipping", shipping, "<ns:n>")
assert expr.evaluate(order) == 10
  • Arguments and the result are converted like the input. None stands for undefined, in both directions: a missing argument arrives as None, and a function that returns None gives an undefined result. A function argument arrives as a jlens.Function (below).
  • A signature (register_function’s third argument) checks the arguments before each call, with the errors of the built-in functions (T0410, T0412). A parameter with - receives the context value when the argument is missing: <n-:n> makes price.$double() work. An invalid signature raises a JlensError.
  • The number of positional parameters before the first with a default value tells higher-order functions how many arguments to pass: $map passes the index only to functions with two or more. A callable whose signature inspect cannot read counts as having none.
  • Any callable works: a function, a lambda, a method, a class, or a built-in such as len.
  • Asynchronous functions are not supported. A coroutine function fails with U1002. Fetch what the expression needs before evaluating it.
  • Precedence: a function in the bindings replaces a registered function of the same name, and both replace a built-in function.

Exceptions

An exception raised by a host function is raised again by the evaluation as is, the same object, with position and token attributes added when it has none:

from jlens import Expression


class RateError(Exception):
    code = "RATE01"  # how evaluate_with_audit reports it


def rate(region):
    raise RateError(f"no rate for {region}")


expr = Expression("$rate(region) * 2")
try:
    expr.evaluate({"region": "west"}, {"rate": rate})
except RateError as error:
    assert (error.position, error.token) == (6, "rate")  # added by jlens

evaluate_with_audit reports it in its error, with its code attribute (or the name of its type) and its text. Inside $eval, it becomes the error of $eval (D3121).

Functions as arguments

A host function can call a JSONata function it receives, such as a step to retry or a fallback: a lambda, a built-in function, a partial application, a chain or another host function. It arrives as a jlens.Function:

def retry(step, times):
    for attempt in range(1, times + 1):
        try:
            return step(attempt)
        except Exception:
            if attempt == times:
                raise


expr = Expression("$retry(function($i) { $lookup(sku, $i) }, 3)")
assert expr.evaluate({"sku": "A1"}, {"retry": retry, "lookup": lookup}) == 7
  • The call is part of the evaluation, as when $map calls its function. The context value is null, and a lambda keeps the variables of its definition. The call counts as a level of depth, so a recursion through a host function ends with D1011; it checks the timeout; its result is limited by max_result_size.
  • Arguments and the result are converted as for a host function. Its arity attribute is the number of parameters the function declares.
  • Errors are raised as a JlensError with their codes, or as the exception a host function raised. The host function can catch them, or let them through, which ends the evaluation with that error.
  • It is valid until the host function returns. Called later, or from another thread, it raises a JlensError with code U1005.

Errors

Errors are jlens.JlensError exceptions, a subclass of Exception. They carry the JSONata error fields; every offset counts code points, the unit of str, so source[error.start:error.end] is the part of the source the error is about:

try:
    Expression("Account.Order[0;]")
except JlensError as error:
    assert error.code == "S0202"
    assert str(error) == 'Expected "]", got ";"'
    assert error.position == 16  # where it was detected, as in jsonata-js
    assert (error.start, error.end) == (15, 16)  # the offending part of the source
    assert error.token == ";"

Evaluation errors carry value too, when there is one (for T2001, the value that is not a number):

try:
    Expression("customer.name + 1").evaluate({"customer": {"name": "Acme"}})
except JlensError as error:
    assert error.code == "T2001"
    assert error.value == "Acme"

str(error) is the message. Match on code, never on the message. Arguments of the wrong type, such as bindings that are not a dict, raise a TypeError instead, and a value that cannot be converted, such as a cyclic binding or invalid JSON text, a ValueError. The error reference lists every code.

The fields an expression reads

reads tells which fields of its input and of each binding an expression may read, without evaluating it (ADR 0016): an application can fetch only those from a database, or know which rules depend on a field. union_reads combines the answers of several expressions.

expr = Expression("$sum(items[type = $kind].(price * quantity)) * $rate(country)")
reads = expr.reads({"rate": lambda country: RATES[country]})
assert reads == {
    "input": {"country": True, "items": {"price": True, "quantity": True, "type": True}},
    "bindings": {"kind": True, "rate": True},
}

union = union_reads([reads, Expression("customer.name").reads()])
assert union["input"]["customer"] == {"name": True}
  • The answer is an upper bound. True reads the value whole; a dict reads only the fields it lists, of an object, or of each item of a list; an empty dict needs the value but none of its fields, as $count does. On its input and bindings cut down that way, an expression gives the same result, or fails with the same error code. Where the analysis cannot follow a value, under * or **, in a constructed object or in the result, it reads the value whole.
  • Pass the bindings the expression will be evaluated with. A Python function does not receive the context of its call, so a call to one in the bindings, or registered on the expression, reads only its arguments, and the context a - parameter may take. A call to a function the analysis does not know may read its context: the whole input, at the top of an expression.
  • "everyBinding": True says the expression may read any binding whole, as $eval can: keep them all. The keys are those of the JSON form, which the other packages and the CLI share.
  • A binding named after a built-in function shadows it during the evaluation, but the analysis takes the name as the built-in’s: such an application cannot cut its input by it.

Document.from_json(text, read) parses JSON text cut by a Read, the "input" of reads() or of union_reads(). It skips the fields the Read leaves out, which on a wide document is several times faster (Performance), and the document serves each expression that went into the union as the whole one would:

rules = [Expression("total > 100"), Expression("customer.tier = 'gold'")]
document = Document.from_json(text, union_reads([rule.reads() for rule in rules])["input"])
assert [rule.evaluate_document(document) for rule in rules] == [True, True]

The fields skipped are checked as JSON syntax only: a number too large for a float, which a full parse rejects, passes there.

Explaining results

evaluate_with_audit evaluates and records how the result was reached; see the audit guide. Evaluation errors are reported in the result, not raised:

from jlens import Expression

expr = Expression('/** @label "Big order" */ $sum(items.(price * qty)) > $limit')
audited = expr.evaluate_with_audit(
    {"items": [{"price": 2.5, "qty": 4}, {"price": 1, "qty": 3}]},
    {"limit": 20},
    level="decisions",
    limits={"max_nodes": 1000},
)
assert audited["result"] is False
assert audited["error"] is None
assert audited["explanation_text"] == (
    "result: false\n✘ Big order — $sum(items.(price * qty)) > $limit → false (13 > 20)\n"
)
root = audited["audit"]["root"]
assert (root["label"], root["operands"], root["outcome"]) == ("Big order", [13, 20], "false")

The options are those of evaluate, plus two more:

  • level is "off", "decisions" (the default) or "full".
  • limits sets the capture limits: max_items, max_string, max_depth, max_rejected, max_nodes and max_source.

The result is a dict (typed as jlens.AuditResult) with result, error, audit, explanation and explanation_text. audit is the audit tree in the JSON format of jlens eval --audit json, with its camelCase field names, and its spans count code points. explanation["lines"] holds structured lines (depth, passed, text, message, node) for rendering in a user interface. The input is converted whole first, as for a Document.

Limits

LimitDefaultError
Evaluation depth (max_depth)50,000D1011
Evaluation time (timeout, seconds)noneD1012
Evaluation steps (max_steps)noneU1006
Length of a string built (max_string_length, bytes of UTF-8)256 MiBU1001
Items of an array built (max_array_length)16,777,216U1001
Size of the result as JSON text (max_result_size, bytes)256 MiBU1001
Expression nesting1,000 levelsU1001
Nesting of arrays and objects in a value that is returned, compared or serialized1,000 levelsU1001

The size of the result counts a value each time it appears, as the JSON text does, and also limits the arguments passed to a host function. The stack grows as needed, so the depth limit is that of the native targets; see the evaluator chapter. There is no cancellation from another thread: use timeout or max_steps.

A timeout reads the clock, so the same evaluation can pass on one machine and fail on another. max_steps does not depend on the machine: each node evaluated is a step, and so is each function a built-in or a host function calls back, and each 1,024 steps of a regular expression’s backtracking. The same expression, input and options take the same steps on every machine, in WebAssembly too, whichever evaluate method reads the input, and fail with U1006 once the budget is spent; the error’s value is the limit. The header of an audit reports the steps an evaluation took (result["audit"]["header"]["steps"]), to set a budget from. See ADR 0018. The performance chapter compares the package’s speed and its behaviour at these limits with the other JSONata packages for Python.

Typing

The package ships type stubs and py.typed. Expression, Document, Function and JlensError are typed, and so are the values evaluate_with_audit takes and returns: AuditResult, ErrorInfo and CaptureLimits, which are TypedDicts, and those reads and union_reads return: Reads, a TypedDict, and Read. Results of evaluate are Any.

What the package leaves out

The language service and schema inference are not in the Python package: editors reach them through the language server, and jlens schema infer infers a schema from the command line. They can be added when a Python application asks for them.

Building from source

The source distribution builds on any platform with Rust 1.88 or later; pip builds it when no wheel fits, such as for free-threaded Python 3.14. From a checkout, with maturin in a virtual environment:

cd crates/jlens-python
pip install maturin pytest
maturin develop                          # builds the package into the active environment
python -m pytest -p no:cacheprovider tests

Java

The Java package io.github.thkprado:jlens runs the jlens engine on the JVM, through a C API that Java calls with the Foreign Function and Memory API, Panama (ADR 0021). It covers evaluation, host functions written in Java, and audit trees with their explanations. Its API is the one of the Python and WebAssembly packages, in Java’s style: one immutable Expression evaluated from any thread, options as a record with a builder, results as maps and lists, and offsets counted in UTF-16 code units, the unit of a String.

<dependency>
  <groupId>io.github.thkprado</groupId>
  <artifactId>jlens</artifactId>
  <version>0.37.0</version>
</dependency>

It needs Java 25 or later. The package is in beta until jlens 1.0: its API may still change in a minor release, as the changelog will say. The installation page lists the platforms its JAR has native libraries for.

The package calls native code. Start the JVM with --enable-native-access, or Java prints a warning at first use, and a later Java release will refuse the access (JEP 472):

java --enable-native-access=io.github.thkprado.jlens -p app.jar:jlens.jar -m app   # on the module path
java --enable-native-access=ALL-UNNAMED -cp app.jar:jlens.jar app.Main            # on the class path

An application packaged as an executable JAR can put Enable-Native-Access: ALL-UNNAMED in its manifest instead; a library’s JAR cannot do it for the application.

The snippets in this chapter come from GuideTest.java in crates/jlens-java/java/src/test/, which the package’s JUnit suite runs.

Compile once, evaluate many times

try (Expression expression = Expression.compile("$sum(items[type = $kind].(price * qty))");
        Bindings books = Bindings.of(Map.of("kind", "book"))) {
    Map<String, Object> order = Map.of("items", List.of(
            Map.of("type", "book", "price", 12.5, "qty", 2),
            Map.of("type", "pen", "price", 1.5, "qty", 10)));
    assertEquals(25L, expression.evaluate(order, books));
    assertEquals("25", expression.evaluateJson(
            "{\"items\": [{\"type\": \"book\", \"price\": 12.5, \"qty\": 2}]}", books));
}

An Expression is compiled once and evaluated any number of times, from any number of threads, virtual ones included. Compiling throws a JlensException on syntax errors.

Expression expression = Expression.compile(source);   // compile once
expression.evaluate(input, bindings, options);        // Java objects in, Java objects out
expression.evaluateFromJson(text, bindings, options); // JSON text in, Java objects out
expression.evaluateJson(text, bindings, options);     // JSON text in, JSON text out
expression.evaluate(document, bindings, options);     // a Document, parsed once
expression.source();                                  // the source text
  • The input is Java objects (Map, List, String, numbers, Boolean, null), JSON text (a String or UTF-8 byte[]), or a Document. See how the input is read.
  • The bindings are variables and host functions, made once: Bindings.of(Map.of("limit", 10)) makes $limit available. Each method also comes without them, and without options.
  • The options are a record: the limits, and the clock and seed that make an evaluation reproducible.
  • The result is built for each evaluation, and the caller may modify it: an object is a LinkedHashMap, its fields in their order; an array an ArrayList; a number a Long when it is integral and in a long’s range, a Double otherwise (1.5, 1e20); and a String, a Boolean or null.

Undefined and null

JSONata tells an undefined result (the expression produced nothing) from null. evaluate and evaluateFromJson return null for both; evaluateJson keeps them apart, with null for an undefined result and the text "null" for null:

try (Expression missing = Expression.compile("missing");
        Expression none = Expression.compile("null")) {
    assertNull(missing.evaluateFromJson("{}"));          // undefined
    assertNull(none.evaluateFromJson("{}"));             // null
    assertNull(missing.evaluateJson("{}"));              // undefined
    assertEquals("null", none.evaluateJson("{}"));       // null
}

Options

try (Expression clock = Expression.compile("[$now(), $random()]")) {
    Options fixed = Options.builder()
            .now(Instant.parse("2024-01-02T03:04:05Z"))
            .seed(7)
            .build();
    List<?> first = (List<?>) clock.evaluate(Map.of(), fixed);
    assertEquals("2024-01-02T03:04:05.000Z", first.get(0));
    assertEquals(first, clock.evaluate(Map.of(), fixed));
}

try (Expression loop = Expression.compile("($f := function($n) { $f($n + 1) }; $f(0))")) {
    Options briefly = Options.builder().timeout(Duration.ofMillis(50)).build();
    JlensException error = assertThrows(JlensException.class, () -> loop.evaluate(Map.of(), briefly));
    assertEquals("D1012", error.code());
}

try (Expression sum = Expression.compile("$sum($map([1..1000], function($i) { $i }))")) {
    Options budget = Options.builder().maxSteps(1000).build();  // the same on every machine
    JlensException error = assertThrows(JlensException.class, () -> sum.evaluate(Map.of(), budget));
    assertEquals("U1006", error.code());
    assertEquals("1000", error.valueJson().orElseThrow());
}
  • timeout (a Duration) stops the evaluation with D1012.
  • maxSteps stops it with U1006 once it has taken that many steps, the same on every machine; see limits.
  • maxDepth, maxStringLength, maxArrayLength and maxResultSize bound the evaluation; see limits.
  • now (an Instant) fixes $now() and $millis().
  • seed fixes $random() and $shuffle().

A component left null keeps its default, and a negative one throws an IllegalArgumentException. The package makes each distinct Options a native object once, so an application that keeps a few of them pays nothing per evaluation for them.

How the input is read

evaluate reads Java objects during the evaluation, one level at a time, when the expression first reaches it, as the Python and WebAssembly packages do (ADR 0010). A path such as customer.name reads one entry of two maps, however large the rest of the input is, and an index (items[0], items[$i]) one item of a list.

JavaJSONata
Map with String keysobject, in the map’s order
Listarray
Stringstring
Integer, Long, Short, Byte, Double, Float, BigInteger, BigDecimalnumber, a double; NaN and the infinities become null, as in JSON
Booleanboolean
nullnull

Anything else, such as a Date, a key that is not a String, or a map or list inside itself, has no JSON form, and a map or list nested more than 1,000 levels deep is not read, as JSON text that deep is not parsed. Three consequences follow from reading the input as the expression goes:

  • Errors appear when their part is read. A value that cannot be read stops the evaluation with U1004 when the expression reads it; one it never reaches does no harm.
  • The input must not change during the evaluation. A host function, or another thread, that modifies it can change what the rest of the evaluation reads. Copy the input first if something must modify it.
  • A map may compute its values. The input can be a view of the application’s own data: a map that computes, or fetches, the value of a field when it is asked for it. A field read by name asks for that field alone, with get, and with containsKey where get gives null. A map read whole (by $keys, by *, or as the context of a call to a function that is not built in) is read once, from size and entrySet, and is not asked again. So the four must agree: a field that get answers and entrySet does not list is found or not according to how the expression reads the map, with no error. A class that extends AbstractMap and writes entrySet alone, with entries that compute in getValue, keeps them in agreement. What a view answers must not change during the evaluation, as for any input; a cache behind it may fill.
List<Object> items = List.of(Map.of("sku", "A1"), Map.of("sku", "B2"));
Map<String, Object> order = Map.of(
        "customer", Map.of("name", "Ada"),
        "items", items,
        "placed", new Date());                           // no JSON form
try (Expression name = Expression.compile("customer.name");
        Expression all = Expression.compile("items");
        Expression text = Expression.compile("$string($)")) {
    assertEquals("Ada", name.evaluate(order));           // reads two fields of two maps
    assertSame(items, all.evaluate(order));              // the list itself, not a copy
    JlensException error = assertThrows(JlensException.class, () -> text.evaluate(order));
    assertEquals("U1004", error.code());                 // reading "placed" failed
}

Evaluations never modify their input. A map or list of the input that the result holds unchanged comes back as itself, not as a copy, as $ returns the input: modifying it modifies the input.

JSON text

evaluateJson takes the input as JSON text and returns the result as JSON text, and evaluateFromJson returns Java objects from JSON text. For a document you already have as text, such as an HTTP response body, they avoid building Java objects only to read them. While they parse, they skip the fields the expression does not read, checking them as JSON syntax only. With bindings that hold host functions, the fields are those of reads(bindings): a call to one of the functions keeps the fields its arguments read, not the whole input.

String body = """
        {"customer": {"name": "Ada", "tier": "gold"}, "log": [{"at": 1}, {"at": 2}]}""";
try (Expression tier = Expression.compile("customer.tier")) {
    assertEquals("\"gold\"", tier.evaluateJson(body));  // "log" is only checked as JSON
    assertEquals("gold", tier.evaluateFromJson(body));
    JlensException error = assertThrows(JlensException.class, () -> tier.evaluateJson("{"));
    assertEquals("U2001", error.code());
}

Invalid JSON, or a byte[] that is not UTF-8, throws a JlensException with code U2001.

Reusing a document

To evaluate several expressions against one document (a set of rules, say), or one expression several times, parse it once:

try (Document order = Document.fromJson("""
                {"total": 120, "customer": {"tier": "gold"}}""");
        Expression big = Expression.compile("total > 100");
        Expression gold = Expression.compile("customer.tier = 'gold'")) {
    assertEquals(true, big.evaluate(order));
    assertEquals(true, gold.evaluate(order));
}

A Document is JSON text parsed once, kept in native memory. An evaluation against it reads no Java objects, so it is the fastest input: items[0].name takes under a microsecond on any size of document (Performance). Evaluations never modify a document.

What a document costs

A document keeps its conversion and its JSON text, both in native memory: it counts against a container’s memory limit and the process’s resident size, not against the Java heap (-Xmx), and a heap dump does not show it. The text is kept so that each operating system thread that evaluates the document can convert it (Threads). Measured through the C API the package calls, on 16 MB of JSON text, an array of 80,000 items of eight fields each (Windows, x86-64):

Native memory, in times the text
A whole document6.8: the conversion 5.8, the text 1
A document cut to items.price2: the conversion 1, the text 1
Each further thread that evaluates itone conversion more
An evaluation against itits working memory, while it runs: 1.1 for $count(items[price > 50]) on the whole document

So a pool of threads multiplies it, in two ways:

  • Threads that each make their own documents, as consumers of a queue do, hold one document each: 16 threads, each with a whole document of 16 MB, hold 1.8 GB; cut, 0.57 GB.
  • One document evaluated by many threads is converted on each, and keeps its text once: 16 threads hold 1.5 GB of the whole document, and 0.3 GB of the cut one.

A document that keeps only the fields its expressions read costs a fraction of the whole one, and its conversion is that much faster. While it is made, the native memory is what it keeps, plus a little: the text the package copies into native memory becomes the document’s, with no second copy. fromJson(String) encodes the text into a UTF-8 byte[] on the heap first; text already in UTF-8 bytes goes to fromJson(byte[]) with no encoding.

Documents as variables

An expression that reads more than one document, such as two versions of a record, or a record and a table it refers to, takes the others as variables. An evaluation against a Document binds documents by name, each the value of its $name:

try (Expression added = Expression.compile("lines[$not(sku in $before.lines.sku)].sku");
        Document before = Document.fromJson(stored);
        Document after = Document.fromJson(received)) {
    assertEquals("b", added.evaluate(after, Map.of("before", before)));
}
  • Nothing is copied. A document bound to a variable is read where it is, as the input is: no Java objects are built from it, and the evaluation converts nothing. A variable of Bindings is converted at each evaluation, as far as the expression reads it, which for a field of each item of a large array is that field of every item. With a variable of 100,000 items, $table.items[0].name takes 8.3 ms from Bindings and 0.8 µs from a Document (macOS, Apple M1).
  • The names are given with or without their $. One document may be bound to several names, and be the input too. With null as the input, the expression runs on its variables alone.
  • Bindings go with them: evaluate(input, documents, bindings). A document takes the place of a variable or a host function of the same name in the bindings, for that evaluation. The bindings stay as they are, built once for every evaluation.
  • evaluateJson takes the same arguments and returns JSON text. An audit (evaluateWithAudit) takes no documents: its variables go in its Bindings.

Each document can keep only the fields the expression reads of its variable, which reads().bindings() gives by name:

try (Expression added = Expression.compile("lines[$not(sku in $before.lines.sku)].sku")) {
    Reads reads = added.reads();
    assertFalse(reads.everyBinding());
    Read read = reads.bindings().get("before");   // "id", "qty" and "history" skipped
    try (Document before = Document.fromJson(stored, read);
            Document after = Document.fromJson(received, reads.input())) {
        assertEquals("b", added.evaluate(after, Map.of("before", before)));
    }
}

A name that bindings() does not list is a variable the expression does not read, and when everyBinding() is true the expression may read any of them whole: keep those documents whole.

Native objects

Expression, Document, Bindings, Schema and LanguageService hold native memory. They are AutoCloseable: close them when done, with try-with-resources or when the application stops. One never closed is freed once it becomes unreachable, by a Cleaner, so forgetting to close costs memory for a while, never a crash. Using a closed object throws an IllegalStateException.

The JAR carries the native library of each platform it supports. At first use, the package copies the library of the running platform to a directory named after its content in java.io.tmpdir, private to the user, and loads it from there. It refuses a directory that another user could write to. Set the system property jlens.library to the path of the library to load it from elsewhere, such as where the temporary directory is mounted noexec.

Threads

Expression, Document and Bindings objects can be shared between threads, virtual threads included:

try (Expression total = Expression.compile("$sum(items.price)");
        Document order = Document.fromJson("""
                {"items": [{"price": 2}, {"price": 3}]}""");
        ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<Object>> results = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        results.add(pool.submit(() -> total.evaluate(order)));
    }
    for (Future<Object> result : results) {
        assertEquals(5L, result.get());
    }
}

An evaluation runs on the calling thread, the carrier thread for a virtual thread, and evaluations of one expression on several threads proceed in parallel. A virtual thread stays on its carrier during an evaluation, as during any native call.

A Document used by several threads is converted once more on each operating system thread, the first time that thread evaluates against it, and a thread keeps its conversion until the document is closed. After that, each thread drops its conversion at its next call into jlens: a carrier thread that never evaluates again keeps at most one conversion per document closed.

The evaluation grows its stack as it needs, so threads with a small stack (-Xss, or a platform thread’s stackSize) work: an evaluation nested too deep stops with D1011 or U1001, never with a crash.

Host functions

Java functions in the bindings are called from the expression like built-in functions. Each has an arity or a signature:

Map<String, Double> rates = Map.of("north", 1.5, "south", 2.0);
try (Bindings bindings = Bindings.builder()
                .function("shipping", "<ns:n>", args ->
                        ((Number) args.get(0)).doubleValue() * rates.get((String) args.get(1)))
                .build();
        Expression expression = Expression.compile("$shipping($sum(items.weight), region)")) {
    assertEquals(10L, expression.evaluate(order, bindings));
}
  • Arguments and the result cross as values: the arguments are the Java objects of a result (LinkedHashMap, ArrayList, String, Long, Double, Boolean, null), and the result is read as the input is, whole, when the function returns. null stands for undefined, in both directions. A function argument arrives as a JsonataFunction (below). A result with no JSON form throws an IllegalArgumentException.
  • A signature checks the arguments before each call, with the errors of the built-in functions (T0410, T0412). A parameter with - receives the context value when the argument is missing: <n-:n> makes price.$double() work. Without a signature, the arity tells higher-order functions how many arguments to pass: $map passes the index only to functions of two or more. An invalid signature throws a JlensException.
  • Asynchronous functions are not supported. A function that returns a CompletionStage or a Future fails with U1002. Fetch what the expression needs before evaluating it.
  • Precedence: a variable and a function cannot share a name in one Bindings, as binding one replaces the other; both replace a built-in function of the same name. There is no registerFunction: Bindings are made once and serve every expression.

A host function bound but not called costs nothing: the evaluation looks it up when a name is not found in its own frames (ADR 0006).

Exceptions

An exception thrown by a host function is thrown again by the evaluation, the same object, unchanged:

IllegalStateException down = new IllegalStateException("the rate service is down");
try (Bindings bindings = Bindings.builder()
                .function("rate", 1, args -> {
                    throw down;
                })
                .build();
        Expression expression = Expression.compile("$rate(region)")) {
    Map<String, Object> order = Map.of("region", "south");
    IllegalStateException thrown =
            assertThrows(IllegalStateException.class, () -> expression.evaluate(order, bindings));
    assertSame(down, thrown);
}

evaluateWithAudit reports it in its error, a JlensException whose cause is the exception. Inside $eval, it becomes the error of $eval (D3121).

Functions as arguments

A host function can call a JSONata function it receives, such as a step to retry or a fallback: a lambda, a built-in function, a partial application, a chain or another host function. It arrives as a JsonataFunction:

HostFunction retry = args -> {
    JsonataFunction step = (JsonataFunction) args.get(0);
    long times = (Long) args.get(1);
    for (long attempt = 1; ; attempt++) {
        try {
            return step.call(attempt);
        } catch (RuntimeException e) {
            if (attempt == times) throw e;
        }
    }
};
try (Bindings bindings = Bindings.builder()
                .function("retry", 2, retry)
                .function("lookup", 2, lookup)
                .build();
        Expression expression = Expression.compile("$retry(function($i) { $lookup(sku, $i) }, 3)")) {
    assertEquals(7L, expression.evaluate(Map.of("sku", "A1"), bindings));
}
  • The call is part of the evaluation, as when $map calls its function. The context value is null, and a lambda keeps the variables of its definition. The call counts as a level of depth, so a recursion through a host function ends with D1011; it checks the timeout; its result is limited by maxResultSize.
  • Arguments and the result are converted as for a host function; arity() is the number of parameters the function declares.
  • Errors are thrown as a JlensException with their codes, or as the exception a host function threw. The host function can catch them, or let them through, which ends the evaluation with that error.
  • It is valid until the host function returns, on its thread. Called later, or from another thread, it throws a JlensException with code U1005.

Errors

Errors are JlensExceptions, an unchecked exception. They carry the JSONata error fields; every offset counts UTF-16 code units, the unit of String, so source.substring(start, end) is the part of the source the error is about:

JlensException error = assertThrows(JlensException.class,
        () -> Expression.compile("Account.Order[0;]"));
assertEquals("S0202", error.code());
assertEquals("Expected \"]\", got \";\"", error.getMessage());
assertEquals(16, error.position().getAsInt());           // where it was detected
assertEquals(15, error.start().getAsInt());              // the offending part of the source
assertEquals(16, error.end().getAsInt());
assertEquals(";", error.token().orElseThrow());

Evaluation errors carry the value too, as JSON text, when there is one (for T2001, the value that is not a number):

try (Expression expression = Expression.compile("customer.name + 1")) {
    JlensException notANumber = assertThrows(JlensException.class,
            () -> expression.evaluate(Map.of("customer", Map.of("name", "Acme"))));
    assertEquals("T2001", notANumber.code());
    assertEquals("\"Acme\"", notANumber.valueJson().orElseThrow());
}

getMessage() is the message. Match on code(), never on the message. The error reference lists every code; the package’s own are U2001 (input that is not JSON), U2004 (a failure inside the native library, which never ends the JVM) and U2005 (options, reads or a JSON Schema not in their form).

The fields an expression reads

reads() tells which fields of its input and of each binding an expression may read, without evaluating it (ADR 0016): an application can fetch only those from a database, or know which rules depend on a field. Reads.union combines the answers of several expressions.

try (Expression expression = Expression.compile("$sum(items[type = $kind].(price * quantity))")) {
    Reads reads = expression.reads();
    assertEquals(new Read.Fields(Map.of("items", new Read.Fields(Map.of(
                    "price", Read.WHOLE, "quantity", Read.WHOLE, "type", Read.WHOLE)))),
            reads.input());
    assertEquals(Map.of("kind", Read.WHOLE), reads.bindings());
    assertEquals("{\"input\":{\"items\":{\"price\":true,\"quantity\":true,\"type\":true}},"
            + "\"bindings\":{\"kind\":true}}", reads.toJson());
}
  • The answer is an upper bound. A Read is Read.WHOLE, the value whole, or Read.Fields, only the fields it lists, of an object, or of each item of an array; empty fields need the value but none of its fields, as $count does. On its input and bindings cut down that way, an expression gives the same result, or fails with the same error code. Where the analysis cannot follow a value, under * or **, in a constructed object or in the result, it reads the value whole. input() is null when the expression does not read its input.

  • A function that is not built in reads the context of its call whole, as reads() does not know it: $tax(price) at the top of an expression reads the whole input. A host function receives its arguments and nothing else, so reads(bindings), given the bindings the expression is evaluated with, takes a call to one of their functions as reading its arguments alone, and the context a - of its signature may take:

    try (Bindings bindings = Bindings.builder().function("tax", 1, args -> 0).build();
            Expression expression = Expression.compile("$tax(price)")) {
        assertEquals(Read.WHOLE, expression.reads().input());   // an unknown function
        assertEquals(new Read.Fields(Map.of("price", Read.WHOLE)),
                expression.reads(bindings).input());
    }
    

    evaluate over Java objects cuts its input by reads(), as an expression serves any bindings; evaluateJson and evaluateFromJson cut the JSON text by reads(bindings) when the bindings hold host functions, as JSON text says, and by reads() otherwise.

  • everyBinding() says the expression may read any binding whole, as $eval can: keep them all. toJson() gives the JSON form, which the other packages and the CLI share.

Document.fromJson(text, read) parses JSON text cut by a Read. It skips the fields the Read leaves out, and the document serves each expression that went into the union as the whole one would:

try (Expression big = Expression.compile("total > 100");
        Expression gold = Expression.compile("customer.tier = 'gold'")) {
    Read read = Reads.union(List.of(big.reads(), gold.reads())).input();
    try (Document document = Document.fromJson(text, read)) {   // "notes" and "log" skipped
        assertEquals(true, big.evaluate(document));
        assertEquals(true, gold.evaluate(document));
    }
}

The fields skipped are checked as JSON syntax only: a number too large for a double, which a full parse rejects, passes there.

Explaining results

evaluateWithAudit evaluates and records how the result was reached; see the audit guide. Evaluation errors are reported in the result, not thrown:

try (Expression expression = Expression.compile(
                "/** @label \"Big order\" */ $sum(items.(price * qty)) > $limit");
        Bindings limit = Bindings.of(Map.of("limit", 20))) {
    Map<String, Object> order = Map.of("items", List.of(
            Map.of("price", 2.5, "qty", 4),
            Map.of("price", 1, "qty", 3)));
    AuditOptions options = AuditOptions.of(AuditLevel.DECISIONS)
            .withLimits(CaptureLimits.DEFAULTS.withMaxNodes(1000));
    AuditResult audited = expression.evaluateWithAudit(order, limit, options);
    assertEquals(false, audited.result());
    assertNull(audited.error());
    assertEquals("result: false\n✘ Big order — $sum(items.(price * qty)) > $limit → false (13 > 20)\n",
            audited.explanation().text());
    AuditNode root = audited.audit().root();
    assertEquals("Big order", root.label());
    assertEquals(AuditNode.Outcome.FALSE, root.outcome());
    assertEquals(new AuditNode.Comparison(13L, 20L), root.decision());
}

It takes Java objects, with Bindings, Options and AuditOptions: a level (OFF, DECISIONS, the default, or FULL) and the CaptureLimits (maxItems, maxString, maxDepth, maxRejected, maxNodes and maxSource). The input is converted whole first, so a Document is refused. The result is an AuditResult record:

  • result() and error(), a JlensException or null;
  • audit(), the AuditTree: its header() (the level, the result, when it ran and for how long, the steps taken), its root() node, nodeCount() and truncated(). An AuditNode is a record: what it evaluated (kind, source, span in UTF-16 offsets, label), its input, output and outcome, the filters it ran, its children, and what it decided as an AuditNode.Decision, a sealed interface: a Comparison and its operands, a ShortCircuit, a Conditional’s branch or a Binding;
  • explanation(), whose text() is the text of jlens eval --explain, and whose lines() are structured lines (depth, passed, text, message, node) for a user interface.

A tree nests as deep as the evaluation did: walk it with a stack or a queue, not by recursion.

Limits

LimitDefaultError
Evaluation depth (maxDepth)50,000D1011
Evaluation time (timeout)noneD1012
Evaluation steps (maxSteps)noneU1006
Length of a string built (maxStringLength, bytes of UTF-8)256 MiBU1001
Items of an array built (maxArrayLength)16,777,216U1001
Size of the result as JSON text (maxResultSize, bytes)256 MiBU1001
Expression nesting1,000 levelsU1001
Nesting of arrays and objects in a value that is read, returned, compared or serialized1,000 levelsU1001

The size of the result counts a value each time it appears, as the JSON text does, and also limits the arguments passed to a host function. The stack grows as needed, so the depth limit is that of the native targets, on any thread; see the evaluator chapter. There is no cancellation from another thread, and interrupting the thread does not stop an evaluation: use timeout or maxSteps.

A timeout reads the clock, so the same evaluation can pass on one machine and fail on another. maxSteps does not depend on the machine: each node evaluated is a step, and so is each function a built-in or a host function calls back, and each 1,024 steps of a regular expression’s backtracking. The same expression, input and options take the same steps on every machine, whichever evaluate method reads the input, and fail with U1006 once the budget is spent; the error’s value is the limit. The header of an audit reports the steps an evaluation took (audit().header().steps()), to set a budget from. See ADR 0018. The performance chapter compares the package’s speed and its behaviour at these limits with the other JSONata implementations for the JVM.

Checking expressions against a schema

A LanguageService checks the text of an expression without evaluating it, against a Schema read from a JSON Schema document (the schema guide; ADR 0023). An application that stores expressions written against a schema checks them again when a new version of the schema arrives:

try (Schema order = Schema.fromJson(orderSchema);
        Schema customer = Schema.fromJson(customerSchema);
        LanguageService service = LanguageService.builder()
                .schema(order)                          // the input
                .variable("customer", customer)         // $customer, and its fields
                .function("discount", "<n:n>")          // $discount, a host function
                .build()) {
    assertEquals(List.of(), service.diagnostics("$discount(total) > $customer.limit"));

    String stored = "status = 'shipped' and totl > 100";
    List<Diagnostic> found = service.diagnostics(stored);
    assertEquals(List.of("W0206", "W0201"), found.stream().map(Diagnostic::code).toList());
    Diagnostic field = found.get(1);
    assertEquals(Diagnostic.Severity.WARNING, field.severity());
    assertEquals("totl", stored.substring(field.span().start(), field.span().end()));
}
  • Schema.fromJson reads a JSON Schema, as text or as UTF-8 bytes. It throws a JlensException with U2001 for text that is not JSON, and with U2005 and the token schema for a JSON Schema that jlens refuses.
  • The builder takes the schema of the input, the variables the expressions are evaluated with, each with the schema of its value or with none, and the host functions, each with its signature or with none. Names are given with or without $. LanguageService.of(schema) is a service of a schema alone, and of(null) checks the syntax and the built-in functions.
  • diagnostics(text) returns a list of Diagnostic records: severity() (ERROR for a syntax error, WARNING for the rest), code(), message() and span(), in UTF-16 offsets as an error’s. The codes and the messages are those of the other packages, the language server and jlens check; the error reference lists them. A text with a syntax error does not throw: its errors are in the list.
  • Variables are checked once one is declared: a variable that is neither declared nor assigned by the expression then gets W0204.
  • Neither object changes once made, and both can be shared between threads. A service keeps what it needs of its schemas, which can be closed as soon as it is built; a new version of a schema is a new Schema and a new LanguageService.

The type of the result, and the context

The builder also says what the expressions are, besides what their schemas say: the type their result must have, as the conditions of a rules engine must give a boolean, and the path whose items they are evaluated against, as the body of items.( … ) (the schema guide). They are those of jlens.json in an editor:

try (Schema order = Schema.fromJson(orderSchema);
        LanguageService conditions = LanguageService.builder()
                .schema(order)
                .resultType("boolean")                  // a rule's condition
                .build();
        LanguageService lines = LanguageService.builder()
                .schema(order)
                .resultType("number")
                .contextPath("items[]")                 // evaluated on each item
                .build()) {
    String vip = "$contains(customer.name, 'VIP')";
    assertEquals("W0214", conditions.diagnostics(vip).getFirst().code());
    ResultType result = conditions.resultType(vip);
    assertEquals(ResultType.Check.MAYBE, result.check());
    assertEquals(List.of("boolean"), result.types());
    Span cause = result.undefined();                    // undefined without a customer
    assertEquals("customer", vip.substring(cause.start(), cause.end()));

    assertEquals(List.of(), lines.diagnostics("price * quantity"));
    assertEquals(ResultType.Check.ALWAYS, lines.resultType("price * quantity").check());
}
  • resultType(types...) takes one JSON type’s name or several, as JSON Schema writes them; "number" accepts an integer. The diagnostics then warn about a result that never has one of them (W0212), may have another (W0213) or may be undefined (W0214). A name that is not a JSON type throws an IllegalArgumentException.
  • contextPath(path) takes the path as Use paths are written, items[] or orders[].items[]: the item is the context of the expressions, and % its parent. A path the schema does not have gives an unknown context, where no field is warned about.
  • resultType(text) returns a ResultType record: types(), the types the result may have (null where they are not known, as without a schema or with a syntax error); undefined() and sequence(), the spans, in UTF-16 offsets, of the operands that may make it undefined or several values, null where none does; and check(), ALWAYS, NEVER, MAYBE or UNKNOWN against the types of resultType, null when the service expects none.

A schema in several documents

A $ref may lead to another document. The package never fetches one: a Schema.Loader takes each document with its URI (the schema guide; ADR 0025):

try (Schema order = Schema.loader()
                .document("https://example.com/schemas/common.json", commonSchema)
                .load(orderSchema);
        LanguageService service = LanguageService.of(order)) {
    assertEquals("W0201", service.diagnostics("customer.nme").getFirst().code());

    // carrier.json was not given: its place is unknown, and nothing is warned under it.
    assertEquals(List.of(), service.diagnostics("carrier.anything"));
    assertEquals(List.of("https://example.com/schemas/carrier.json"),
            order.missingDocuments());
    UnresolvedRef carrier = order.unresolved().getFirst();
    assertEquals("#/properties/carrier", carrier.place());
    assertEquals("carrier.json", carrier.reference());
}
  • Schema.loader() takes document(uri, text) for each other document, as text or as UTF-8 bytes, and uri(uri) for the URI of the schema itself, which its $refs are resolved against when it has no $id. load(text) reads the schema; a document that is not JSON fails it with U2001.
  • A $ref that is not followed does not fail the load. Its place is unknown: nothing is warned under it, and what an expression uses marks it unknown(), so that a load with the document shows as a change.
  • schema.unresolved() lists those $refs as UnresolvedRef records: place(), where it is written; reference(), its text; uri(), what it resolves to; and document(), the URI of the document to give, null when the document is there without that place. schema.missingDocuments() lists the documents to give, each once.
  • schema.unread() lists the keywords the load did not read, whose places are unknown as well, as UnreadKeyword records: place(), the schema that has one, and keyword() ($dynamicRef, $recursiveRef, or a type that names no JSON type; the schema guide lists the keywords).
  • schema.openTuples() lists the tuples that say nothing of the items after them, as OpenTuple records with their place(). They are read, unlike the places above, but any item may follow them, so their items are checked only at a literal index inside the tuple, which may be less than the schema’s author meant (the schema guide says what closes one). These lists are read with the schema, and are there after it is closed.

What an expression uses of its schema

Diagnostics tell whether a stored expression still passes with a new version of its schema. They do not tell whether something it uses changed while the expression stays valid: an enumeration that gained held leaves status = 'open' passing, and the expression may need a case for it. uses tells what the schema says of each field an expression reads, and changes compares two such answers (the schema guide describes both):

String stored;   // kept beside the expression
try (Schema order = Schema.fromJson(orderSchema);
        LanguageService service = LanguageService.of(order);
        Expression expression = Expression.compile("active = true and status = 'open'")) {
    Uses uses = service.uses(expression);
    Use active = uses.input().get("active");
    assertEquals(List.of("boolean"), active.types());
    assertEquals(true, active.required());
    assertEquals(List.of("open", "closed"), uses.input().get("status").enumeration());
    stored = uses.toJson();
}

// Later, with the new version of the schema: the diagnostics see that active is now a
// string, not that status may now be held.
try (Schema order = Schema.fromJson(newOrderSchema);
        LanguageService service = LanguageService.of(order);
        Expression expression = Expression.compile("active = true and status = 'open'")) {
    List<String> codes = service.diagnostics("active = true and status = 'open'").stream()
            .map(Diagnostic::code)
            .toList();
    assertEquals(List.of("W0210"), codes);

    UsesChanges changes = Uses.fromJson(stored).changes(service.uses(expression));
    assertFalse(changes.isEmpty());
    UsesChanges.UseChanges active = changes.input().changed().get("active");
    assertEquals(List.of("boolean"), active.types().before());
    assertEquals(List.of("string"), active.types().after());
    UsesChanges.EnumChange status = changes.input().changed().get("status").enumeration();
    assertEquals(List.of("held"), status.added());
    assertEquals(List.of(), status.removed());
}
  • A host function declared to the service reads its arguments alone, as a HostFunction receives nothing else: $describe(items[0]) uses items, not the whole input, which every change of the schema would be a change of. A function that is not declared reads its context whole.
  • service.uses(expression) returns a Uses record: input(), a map from each path the expression reads of its input to a Use, null when it does not read it; bindings(), the same for each variable; and everyBinding(). A Use has what the schema says of the path: types(), enumeration() and closed(), domain(), format(), required(), and unknown() for a field the schema does not declare. The values of an enumeration are JSON values: a String, a BigDecimal, a Boolean, null, a List or a Map.
  • toJson() and Uses.fromJson write and read the JSON form, the one every jlens package gives: keep it beside the expression. Compare two answers with changes or equals, not by their text.
  • old.changes(current) returns a UsesChanges record, and needs neither schema nor service. isEmpty() says that nothing the expression uses changed. input() and each entry of bindings() are PathChanges: the paths added() and removed(), each with its Use, and the paths changed(), each with a UseChanges whose components are null where nothing changed and a Change with before() and after() where something did; an enumeration also gives the values added() and removed(). toJson() writes the form of the other packages, in which the two sides are old and new.
  • The records cannot be changed, and none holds native memory.

The fields of a schema

An application that builds its own list of attributes, or matches the fields of two versions of a schema, takes them from fields(), without walking the schema (the schema guide says what each holds):

try (Schema order = Schema.fromJson(orderSchema);
        LanguageService service = LanguageService.of(order)) {
    List<ListedField> fields = service.fields();
    assertEquals(List.of("$", "lines", "lines[]", "lines[].sku", "status"),
            fields.stream().map(ListedField::path).toList());
    ListedField status = fields.get(4);
    assertEquals("Status", status.label());
    assertEquals(true, status.required());
    assertEquals(List.of("open", "closed"), status.enumeration());
    assertEquals("A17", status.extensions().get("x-attribute-id"));
    assertEquals("array<object>", fields.get(1).typeSummary());
    assertEquals("products", fields.get(3).domain());
}
  • service.fields() returns a ListedField for each path of the schema of the service’s input, in the order of the paths, which are those of uses: path(), typeSummary() (as completion shows it), types(), required() (null for the value itself and for the items of an array), label(), description(), enumeration() and closed(), domain(), format(), and extensions(), the field’s own x- keywords as written, such as a key of the application’s. A hidden field is left out, with what is under it.
  • The records cannot be changed, and none holds native memory.

Fields renamed by a new version

When a new version of a schema renames fields, rename rewrites an expression written against the old one, given a table of paths, each old path to its new one, here built from the two versions’ fields(), matched by a key of the application’s (the schema guide says what it renames and why it may not be sure):

try (Schema old = Schema.fromJson(version1);
        Schema current = Schema.fromJson(version2);
        LanguageService before = LanguageService.of(old);
        LanguageService after = LanguageService.of(current);
        Expression rule = Expression.compile(
                "status = 'open' and $sum(lines.(qty * price)) > 100")) {
    // The table, from the two versions' fields matched by the application's key.
    Map<Object, String> byKey = new HashMap<>();
    for (ListedField field : after.fields()) {
        Object key = field.extensions().get("x-attribute-id");
        if (key != null) byKey.put(key, field.path());
    }
    Map<String, String> renames = new TreeMap<>();
    for (ListedField field : before.fields()) {
        String path = byKey.get(field.extensions().get("x-attribute-id"));
        if (path != null) renames.put(field.path(), path);
    }
    Renamed renamed = before.rename(rule, renames);
    assertEquals("status = 'open' and $sum(items.(quantity * price)) > 100",
            renamed.text());
    assertEquals(List.of(), renamed.unsure());
    // The rewritten rule uses nothing the new version does not have.
    try (Expression migrated = Expression.compile(renamed.text())) {
        assertTrue(after.uses(migrated).input().values().stream()
                .noneMatch(Use::unknown));
    }
}
  • service.rename(expression, renames) returns a Renamed: text(), the rewritten expression; edits(), each name replaced with its Span; and unsure(), the places it leaves as written, each with its Span, path() and reason() (WHOLE, STRING, MIXED or LOST). Spans are UTF-16, as Java strings count.
  • A table that is not one of renames throws a JlensException with U2005.

What the package leaves out

Completion, hover and signature help, which serve a person typing, are not in the Java package: editors reach them through the language server and the WebAssembly package. Schema inference is not either: jlens schema infer writes a JSON Schema from sample documents, which Schema.fromJson reads. They can be added when a Java application asks for them.

Building from source

From a checkout, with Rust and a JDK 25 or later:

cargo xtask java          # builds the native library, then runs mvnw verify in crates/jlens-java/java

The JAR in crates/jlens-java/java/target then carries the library of the host platform only.

Audit and explainability

A JSONata expression returns a value. jlens can also tell you why it returned that value:

  • which checks passed and which failed;
  • what the compared values were;
  • which items a filter rejected;
  • which values were bound to variables.

The same evaluation, with the same result, produces an audit tree. An explanation is a readable summary of that tree.

A complete example

fixtures/shipping-rule.jsonata decides whether a store order gets free shipping. Its conditions carry annotations:

$approved := (
  /** @label "Authorized customer" @message "The customer login must be on the approved partners list." */
  customer.login in ["alice.walker99", "bob.harrison42"]
  and
  /** @label "Minimum order grand total" @message "The order grand total must exceed 50,000.00." */
  $total > 50000
  and …
);

When a order grand totals only 37,000, jlens eval --explain prints:

$ jlens eval -f fixtures/shipping-rule.jsonata -i order.json --explain
result: {"action":"REGULAR_FEE","code":"SHIP_FEE_402","delivery":"SLOW"}
• $total := $sum(items.(unitPrice * quantity)) = 37000
• $electronics := $sum(items[type = 'electronic'].(unitPrice * quantity)) = 17000
  • [type = 'electronic']: 2 of 3 items passed; rejected: {"code":"1","color":"blue",…}
• $blueTax := $sum(items[color = 'blue'].tax) = 1500
• $averageTax := $average(items.tax) = 2833.3333333333335
✘ $approved := ( customer.login in [...] and ... ) = false
  ✘ Minimum order grand total — $total > 50000 → false (37000 > 50000)
      The order grand total must exceed 50,000.00.
• $approved ? { ... } : { ... } → {"action":"REGULAR_FEE",…} [else]

The explanation follows only the decisions that mattered. The and chain failed, so it shows only the operand that failed, with its business message. The checks that passed are left out. For an approved order, every check is listed with ✔.

In Rust

#![allow(unused)]
fn main() {
use jlens_core::audit::{AuditOptions, explain};
use jlens_core::{Bindings, Expression, Options};

let rule = Expression::compile(&rule_source)?;
let (result, audit) = rule.evaluate_audited(
    Some(&document),
    &Bindings::new(),
    &Options::default(),
    &AuditOptions::decisions(),
);
println!("{}", explain(&audit));              // text
let json = serde_json::to_string(&audit)?;    // the full tree, e.g. to store with the decision
}

evaluate_audited returns the audit even when the evaluation fails. The error is in audit.header.error, and on the node that raised it.

What is recorded

The audit tree mirrors the evaluation, not the syntax: a node evaluated three times (once per item, or once per function call) appears three times. Each AuditNode has these fields:

FieldMeaning
node, kind, op, span, sourceThe syntax-tree node, its type, its operator or function, its location and text
label, message, checkIdFrom the node’s annotation
output, outcomeThe value produced, and whether it was true, false, another value, undefined, or an error
operandsFor comparisons: the two values compared
shortCircuitedFor and/or: the right side was not evaluated
branchFor conditionals: then, else or none
bindingFor $x := …: the variable bound
filtersPredicate filters applied: items tested, items passed, and a sample of rejected items
inputThe context value (level full only)
childrenRecorded evaluations nested inside this one

The header records:

  • the engine version;
  • FNV-1a hashes of the expression and of the input document, so you can tell later exactly what was evaluated;
  • the evaluation timestamp (the value of $now()) and its duration;
  • the result, or the error.

Levels

LevelRecordsTypical use
decisions (default)The root, plus nodes that decide: comparisons, and/or, conditionals, bindings, nodes producing booleans, nodes with filters, annotated nodesExplanations, storing the reasons for a decision
fullEvery evaluated node, with its inputDebugging an expression
offOnly the headerRecording what was evaluated and the result

At level decisions, nodes that decide nothing are collapsed: their recorded descendants move up to the nearest recorded ancestor. Inside a filter, the per-item evaluations are summarized into the filter’s statistics instead of being recorded one by one.

Bounds

Audits of large documents stay bounded. CaptureLimits sets:

LimitDefaultEffect
max_items10Items (or object fields) kept per captured value; the rest becomes "… N more"
max_string200Characters kept per string; longer strings end with …
max_depth4Nesting depth kept in captured values
max_rejected5Rejected items kept per filter
max_nodes10,000Recorded nodes, the root included; past it, a node is dropped, its recorded descendants and filters going to its parent, and truncated is set. A cut tree holds node_count nodes, all reached from the root
max_source200Characters of source text kept per node

Event logs and custom tracers

Auditing is built on a lower-level interface, the Tracer trait. The evaluator calls a tracer’s methods as it goes:

  • enter/exit for each node;
  • operands for each comparison;
  • short_circuit, branch and bind;
  • filter_begin, filter_item and filter_end for filters.

You can implement your own tracer, for example to collect metrics, and pass it to Expression::evaluate_traced. jlens provides three:

TracerOutput
AuditCollectorThe AuditTree described above
JsonlTracerOne JSON object per event (jlens eval --trace-log events.jsonl)
TracingTracer (feature tracing)Events on the tracing target jlens::eval: entries and exits at TRACE, decisions at DEBUG

Performance

When no tracer is attached, auditing costs one check per evaluated node. Compared with the evaluator before tracing existed, interleaved benchmark runs measured between −5.7% and +2.7% across five workloads, within the noise of the machine. With a tracer attached, evaluation does more work in proportion to what is recorded. Level decisions is the cheapest useful level: for the shipping rule on a 200-item document, it takes about three times as long as an evaluation without a tracer, and full about fifteen times. cargo bench -p jlens-core -- audit measures this; see Performance.

Limitations

  • Node spans refer to the expression’s own source. For expressions evaluated through $eval, and for the internal helper behind function composition ($f ~> $g), the reported source snippets refer to a different text.
  • The audit captures values as JSON. Functions appear as "<function>", and undefined values are omitted.

Schema and autocomplete

jlens can learn the structure of your documents from samples and use it to help people write expressions. The language service then provides:

  • completion of field names that knows which object you are in;
  • warnings for fields that do not exist;
  • hover documentation;
  • signature help for functions.

The jlens-schema crate provides both parts, and the CLI and the WebAssembly package expose them.

1. Infer a schema from samples

$ jlens schema infer samples/*.json -o order.schema.json
inferred from 120 sample(s): order.schema.json

Glob patterns are expanded by jlens itself, so they also work in Windows shells. With --each, a sample file holding a top-level array counts as one sample per item.

Inference records, for every place in the documents:

WhatHow
TypesEvery JSON type seen. integer is used while all numbers are written without a fraction; 1500.0 makes it number
FieldsIn first-seen order, with required when every object had the field, and the fraction of objects that had it otherwise
Array itemsThe merged shape of all items of all arrays seen at that place
Arrays never emptyminItems: 1 when no array seen at that place was empty
NumbersMinimum and maximum
String formatsdate-time, date, time, email, uuid or uri, when every string seen has that format
EnumerationsWhen the values come from a small set (at most 10) and repeat
ExamplesUp to three distinct values

The result is a standard JSON Schema 2020-12 document. JSON Schema is a specification for describing the shape of JSON documents; new to it, start with its step-by-step introduction or the guide Understanding JSON Schema. Fields that are not required carry x-jlens-presence, the fraction of objects that had them, and an inferred enum carries x-jlens-enum-inferred: it lists the values seen, not every value allowed, so the language service completes them but never warns about another one. Remove the keyword once the list is complete, or set the values in the overrides (below). An inferred minItems carries x-jlens-min-items-inferred: the language service takes it as it takes an inferred required (the result’s type counts on it), so review both, and remove a minItems where an empty array is allowed. You can commit the file, review it, and edit it like any JSON Schema. jlens also reads JSON Schemas written by hand or by other tools: it follows $ref, by JSON Pointer, $id and $anchor, merges the branches of allOf, and reads those of anyOf and oneOf as one branch or another (the keywords jlens reads lists the others).

A schema may be recursive: a tree whose children are {"$ref": "#"}, a definition that refers to itself, definitions that refer to each other. Completion, hover and the diagnostics follow it as deep as the expression goes, so that children.children.children.nane is warned about as nane is. A $ref that leads nowhere but to itself says nothing of its place: nothing is completed or warned about under it. In the Rust crate such a $ref is kept as a reference to a definition of the schema (ADR 0024): Schema::shape_at follows it, and Schema::members gives the shapes that one stands for. A path of the overrides that goes through it changes the definition, and so every place that refers to it: in that tree, children[].label describes the label of every node.

A schema in several documents

A $ref may lead to another document ("$ref": "common.json#/$defs/person"). jlens never fetches one: the application gives the documents, each with its URI, and the load reads only those (ADR 0025).

#![allow(unused)]
fn main() {
use jlens_schema::SchemaLoader;

let (schema, report) = SchemaLoader::new()
    .document("https://example.com/schemas/common.json", &common)
    .load(&order)?;
for unresolved in &report.unresolved {
    eprintln!("{}: {} was not followed", unresolved.place, unresolved.uri);
}
}

A $ref is resolved against the $id of the schema it is in, or the URI its document is given with (load_at), and a document is known by that URI and by each $id in it. With neither, a reference is taken as written: common.json#/$defs/person is a place of the document given as common.json.

A $ref the load cannot follow does not fail it. Its place is left unknown, so that nothing is completed or warned about under it, and the rest of the schema is checked as usual. The report beside the schema lists each one: where it is written, what it resolves to, and the document that was not given (report.documents() lists them, each once). What an expression uses marks such a place unknown, so a document given later shows as a change. Only a document that is not a schema, or one nested more than 64 levels deep, fails to load.

Schema::from_json_schema is that load with no other document and without the report.

Every package that reads a schema takes its documents and gives the report, in the same JSON form ({"unresolved": [{"place", "reference", "uri", "document"}], "unread": [{"place", "keyword"}], "openTuples": [{"place"}]}, {} when every $ref was followed, every keyword read and no tuple open; unread and openTuples are described below):

WhereThe documentsThe report
RustSchemaLoader::document, or load_asking with a function that gives themLoadReport
WebAssemblynew LanguageService({ schema, sources: { uri, documents } })schemaReport(schema, { uri, documents })
JavaSchema.loader().document(uri, text).load(text)schema.unresolved(), schema.missingDocuments(), schema.unread(), schema.openTuples()
CLI and language serverthe files beside the schema’sa warning for each document not found and for each keyword not read, and one for the open tuples

The CLI and the language server read a document from a file, and never from the network. The file is the one at the same relative path from the schema’s file as between the two URIs: beside schemas/order.json, "$ref": "common.json" is schemas/common.json and "$ref": "../shared/money.json" is shared/money.json, whether the schema has an $id (the path between https://example.com/schemas/order.json and https://example.com/schemas/common.json is common.json) or not. A document on another host, or one with no file there, is not read. A variable’s schema in jlens.json refers to files from the folder of jlens.json. For each document that was not found, each $ref to a place its document does not have, and each keyword not read, jlens check, jlens schema uses and jlens schema complete print a warning: line on standard error, and one more that names the open tuples, and the language server shows a message for each line; the exit code does not change, and --deny-warnings counts the warnings of expressions only. A file that is there and is not JSON fails the command, as a schema that is not JSON does.

In the Rust crate, SchemaLoader::load_asking is that loop: it asks a function for each document the load misses, with its URI and its relative path from the schema, then for the documents those refer to, each URI once and no more than 256.

What JSON Schema has no keyword for travels in jlens’s own x-jlens-* keywords, which other tools ignore. jlens writes them and reads them back, so they can also be written by hand:

KeywordMeaning
x-jlens-presenceOn a field that is not required: the fraction of objects that had it, from 0 to 1
x-jlens-enum-inferredThe enum lists the values seen in the samples, not every value allowed: completion offers them, but a value outside them is not warned about
x-jlens-min-items-inferredThe minItems comes from the samples: no array seen there was empty
x-jlens-domainAn open domain: an identifier naming a list of values only the application can fetch
x-jlens-hiddentrue hides the field from completion, like hidden in the overrides (below); it is still known, so it is not reported as unknown, and hover shows it
x-jlens-samplesAt the root: the number of sample documents the schema was inferred from. For information only: nothing depends on it

A field’s label is written as the standard title, and its description as description.

The keywords jlens reads

The diagnostics warn about what a schema does not allow: a field it does not list, a type it does not give. A keyword that allows more, left unread, would make them warn about what the schema allows; a keyword that only narrows what a place may hold cannot, and jlens leaves those out. So each keyword of JSON Schema (2020-12 and the drafts before it) and of OpenAPI 3.0 is read, left out because it only narrows, or reported. What each keyword means is in the JSON Schema reference.

Keywords
Readtype, properties, required, patternProperties, additionalProperties, unevaluatedProperties (as additionalProperties, where that is absent), items, prefixItems, additionalItems, unevaluatedItems, minItems, maxItems, enum, const, format, minimum, maximum, $ref, $id, $anchor, $defs, definitions, allOf, anyOf, oneOf, if with then and else, dependentSchemas, dependencies, nullable, title, description, examples, x-jlens-*
Left out: they only narrownot, minLength, maxLength, pattern, multipleOf, exclusiveMinimum, exclusiveMaximum, uniqueItems, contains, minContains, maxContains, minProperties, maxProperties, propertyNames, dependentRequired, contentEncoding, contentMediaType, contentSchema
Left out: they describedefault, deprecated, readOnly, writeOnly, $comment, $schema, $vocabulary, $dynamicAnchor, $recursiveAnchor, discriminator, xml, externalDocs, example
Reported$dynamicRef and $recursiveRef, which the scope of a validation resolves; a type that names no JSON type, such as "int"

How some are read:

  • allOf: every branch holds, so its branches are merged with the rest of the schema: a field that one branch requires is always there, even where another branch lists it and does not require it. So do a $ref and the keywords beside it.
  • required holds wherever it is written: beside properties, in a branch of allOf or beside a $ref whose other parts list the field, or with no properties at all. A field it names that nothing lists is a field whose shape is not known, so "required": ["id"] makes id a field that is always there; an object that lists no field otherwise still has any other. In the branches of anyOf and oneOf, a field is required only where every branch requires it.
  • anyOf and oneOf: a value has the shape of one branch or another. It may have the types of any branch, and a field is required only where every branch requires it: with anyOf of a person with a name and a company with a tax, name may be absent, and a result that needs it gets W0214. A field that several branches declare has the types of any of them, and an enum or a const lists the values of every branch, where each lists them (a branch of null alone lists null). A branch that gives no type, such as {} or {"minLength": 1}, leaves the type unknown, as any value may match it, but for one with const or enum, whose type is that of its values; a type beside the anyOf still holds. oneOf is read as anyOf: that only one branch matches only narrows.
  • then and else, read only beside if, and the schemas of dependentSchemas and of draft-07’s dependencies hold for some of the values only. The fields they declare, at any depth, are fields the object may have, none required; a field that then makes a string and else a number is either. What else they say only narrows, and is left out.
  • A tuple, prefixItems or draft-07’s items as an array, has its items merged with those of the rest (items after prefixItems, additionalItems, unevaluatedItems), as a step over the array takes them all. With no schema for the rest, any item may follow, and the items are not known, unless maxItems keeps the array to the tuple or the rest is false; the schema keeps that bound, and writes such a tuple back with "items": false. A literal index inside the tuple has the type of its position, whether items may follow or not: with point a tuple of two numbers, point[1] is a number and point[1] > "a" gets W0208, and after entry[1]. completion offers the fields of the second item. An index from the end, one past the tuple or a computed one (point[-1], point[2], point[$i]) has the type of every item. An override at point[] sets each position as well.
  • enum and const with no type give the types of their values, as every value is one of them: {"enum": ["open", "closed"]} is a string, and {"enum": [1, "a", null]} a number, a string or null. A type, or one that a $ref or a branch of allOf gives, holds as written.
  • nullable: true adds null to the types a schema gives, and to its enum.

A reported keyword leaves the place of its schema unknown, as a $ref that was not followed does: nothing is completed or warned about under it. The report beside the schema lists each one under unread, with place, the schema that has it (#/properties/children/items), and keyword. The CLI and the language server warn about each, as they do about a document not found.

A tuple with no schema for the rest and no maxItems that keeps the array to it is read, and its positions are typed, but it may say less than its author meant: JSON Schema allows any item after it, so point.($ > "a") and point[2] are not checked for a point meant as two numbers. The report lists each one under openTuples, with its place (#/properties/point), and the CLI and the language server name them in one warning. "items": false after prefixItems, "additionalItems": false in draft-07, or maxItems closes the tuple; true in place of false says that it is open on purpose, and it is no longer listed. Nor is a tuple whose schema knows its items by a $ref or a branch of allOf.

Left out, a narrowing keyword can still leave the typing less sure than the schema is: with not: {"type": "null"}, a field may still be null to it, and a field that then requires may still be absent.

2. Describe the fields

Samples tell jlens what fields exist, but not what they mean. Overrides add that information. An overrides file maps paths to settings; [] steps into array items:

{
  "items[].type": {
    "description": "Product category used for catalog classification",
    "enum": ["apparel", "electronic", "toy"]
  },
  "items[].tax": { "label": "Import tax" },
  "customer.login": { "description": "Login chosen at sign-up" },
  "internalRevision": { "hidden": true }
}
SettingEffect
descriptionShown in completion and hover
labelA display name, shown in bold
enumThe allowed values
domainAn open domain: values the application provides (see Open domains)
examplesExample values
formatA format name
typeReplaces the inferred types: one name such as "integer", or a list such as ["string", "null"], as in JSON Schema. The names are JSON Schema’s: null, boolean, integer (a number without a fraction), number, string, array and object
hiddenNever suggested by completion
$ jlens schema infer samples/*.json --overrides overrides.json -o order.schema.json

A path that does not exist yet is created, so overrides can also declare fields that are absent from the samples. A misspelt path does the same, so jlens schema infer warns about each such path, naming the existing path it most likely meant:

warning: override path items.type is not in the samples; declared (did you mean items[].type?)

In Rust, Schema::missing_override_paths lists them before apply_overrides creates them (missingOverridePaths in the Wasm package).

3. Use it

In the terminal

$ jlens check --schema order.schema.json -f rule.jsonata
warning[W0201]: Field "unitprice" is not in the schema; did you mean `unitPrice`?
 --> rule.jsonata:4:22
  |
4 |   $sum(items[type = 'x'].unitprice)
  |                      ^^^^^^^^^

$ jlens schema complete --schema order.schema.json "items[type = 'electronic']."
code                     field     string
color                    field     string
type                     field     string
unitPrice                field     number
quantity                 field     integer
tax                      field     number

--cursor N sets the cursor position in characters, and --json prints the full completion items.

In Rust

#![allow(unused)]
fn main() {
use jlens_schema::{FunctionDecl, LanguageService, Schema};

let schema = Schema::from_json_schema(&serde_json::from_str(&schema_text)?)?;
let service = LanguageService::new(Some(schema))
    .with_variable("approved", None)         // variables the rule is evaluated with
    .with_function(                          // and its host functions
        FunctionDecl::new("shipping", "Shipping cost of a weight to a region")
            .signature("<ns?:n>")
            .params(["weight", "region"]),
    );

let completions = service.complete(text, cursor_byte_offset);
let diagnostics = service.diagnostics(text);
let hover = service.hover(text, cursor_byte_offset);
let help = service.signature_help(text, cursor_byte_offset);
}

Declare the host functions the expressions are evaluated with: they are completed first, and hover and signature help show their signature, parameters and summary. A declared function replaces a built-in function of the same name, as it does during evaluation.

All offsets and spans in the Rust API are byte offsets into the expression text. The WebAssembly package converts them to and from the UTF-16 offsets that browsers and editors use; an application that builds the service into a module of its own converts them with jlens_core::Offsets.

In the browser

The WebAssembly package exposes the same service for editors such as CodeMirror and Monaco; see the WebAssembly guide.

What completion understands

Completion knows the context at the cursor, that is, which object the next field name will be looked up in. It follows the evaluator’s rules:

You typeSuggested
items. or items[...].Fields of an item (arrays are flattened, as during evaluation)
items[ … ]Inside the predicate: fields of an item
items{ … } / items^( … )Fields of an item, in group-by keys and values and in sort keys
$sum(items.( … ))Fields of an item, inside a block applied to each item
($i := items[0]; $i.Variables keep the type of what was assigned to them
items@$it. … $it.Focus variables bind the items of their step
$map(items, function($i){ $i.Callback parameters of $map, $filter, $single, $sort and $reduce get the item type
$sort(items, …)[0].Functions that return their input ($sort, $filter, $reverse, …) keep its type
items.%., items[%. … ], items.code.%.The parent: fields of the object the step that % refers to is evaluated against, the order for an item of items
items.`tyField names that need backquotes
$suVariables in scope, then declared host functions, then built-in functions
customer.login (after a space)Operators: and, or, in
type = , type != , type in [, type in ["toy", The values of type’s enumeration first, then fields, variables and functions
type = "apThe string values of type’s enumeration that start with ap

Each field suggestion carries:

  • its type (string, array<object>, integer | null, …);
  • its label and description;
  • its presence, for optional fields;
  • its allowed values or examples.

Field names that are not plain identifiers are inserted with backquotes, and hidden fields are never suggested.

Values (kind value) come from the enumeration of the left-hand side of =, != or in: a schema’s enum or const, one set in the overrides, or one inferred from samples. examples are not offered, as they are not every value. A value is inserted as a JSONata literal, a string quoted and escaped. Inside quotes the whole literal is replaced, and the string keeps single quotes when it can (JSONata has no \' escape). In an array after in, the values already listed are left out.

Open domains

An enum is a closed list, written with the schema. Some fields take their values from a list only the application can fetch, often a large one, such as customers or products. Such a field names its domain, an identifier only the application understands: x-jlens-domain in the JSON Schema, or domain in the overrides:

{ "customer.login": { "domain": "customers" } }

At the positions where values are completed, the completions then carry, beside their items, a value request (Completions::value_request): the domain, the field’s path in the schema (customer.login; none for a variable), the prefix typed so far, the range a value replaces and the quote it is written with. The service stays synchronous: the application fetches the values that match the prefix, caches them as it sees fit, and writes each as a JSONata literal with ValueRequest::literal (valueLiteral in the Wasm package). Values the field also declares in an enum are still completed as items. A value outside an open domain is never warned about, and hover names the domain.

The values of one domain often depend on another value: the subgroups of a group, the states of a country. The request carries the fields already fixed beside the value, its conditions: each field compared with a literal by =, or with an array of literals by in, that is joined to the value’s comparison by and, in the same predicate or, outside any, in the whole expression. In items[categories[group = 'Electronics' and subgroup = '|, the request for subgroup has the condition items[].categories[].group = ["Electronics"], read from the expression as it is typed, unfinished. A comparison on one side of or, by !=, with something that is not a literal, inside a call such as $not(...) or in another predicate is not a condition. The request also says whether the value is an element of the array of in [...] (in_array), where the application may insert several values, separated by commas, and which literals that array already holds (listed), so that the application does not offer them again, as the service does not complete a declared value twice.

Completion works on incomplete expressions too, such as $count(items[ or items[type = 'x' and . That is the normal state of an expression while someone types it.

Diagnostics

LanguageService::diagnostics returns:

  • syntax errors, from the recovering parser;
  • annotation warnings;
  • W0201 warnings for field names the schema does not have, with a “did you mean” suggestion when a field name is close. Under the parent operator, items.%.custmer, the field is looked up in the parent; where the typing does not tell the parent, as for a step inside parentheses (customer.(login).%), nothing is reported;
  • W0202 warnings for calls of unknown functions, with the same kind of suggestion, and W0203 warnings for calls with too few or too many arguments for the function’s signature. These need no schema. A function is known when it is built in, declared with LanguageService::with_function (or in jlens.json), or bound anywhere in the expression; a variable declared with with_variable may hold a function, so its calls are not checked;
  • W0205 warnings for arguments whose type the function’s signature cannot accept, such as $sum(items.name) when name is a string. Only types that are known count: literals, the results of operators, and fields of the schema. A field that is absent passes any signature; the warning means that the call fails whenever the field is present;
  • W0204 warnings for variables that are not declared, with a suggestion, when at least one variable is declared with with_variable (or in jlens.json): the declarations are then taken to be complete. Names bound in the expression, and functions, are known;
  • W0206 warnings for a literal compared with a field, by =, != or in, that is not one of the field’s declared values, such as items[type = "aparel"]: the comparison is always false. A string gets the nearest value as a suggestion (did you mean "apparel"?). Only an enum or const of the JSON Schema, or an enum set in the overrides, counts: one inferred from samples (x-jlens-enum-inferred) is a guess, and is never warned about, and neither is a field with an open domain. Values that are not literals, such as type = color, are not checked;
  • warnings for the operands of an operator whose types it cannot take, so that the expression fails whenever they are present, or a comparison is always false. With total a string, total > 1000 gets W0208: strings and numbers are not compared with each other (T2009 when it runs). A side of <, <=, > or >= that is a boolean, null, an object or an array of them has no order, W0207 (T2010), and a side of +, -, *, / or % that is not a number gets W0209 (T2001, T2002), as does the operand of a negation, -x, with W0211 (D1002). With active a string, active = true gets W0210: a field compared by =, != or in with a literal of another type is never equal to it. A field with a declared enumeration gets W0206 there instead, and two literals compared are left alone. As for W0205, only types that are known count, an absent field passes, and an array stands for its items: scores > 1 gets none of these when scores is an array of numbers, but W0215, below;
  • W0215 for an operand that may be several values. A path over several items gives a sequence: items.qty > 1 is true for an order of one item and fails for two (T2010), items.qty + 1 fails too (T2001), and items.qty = 2 is false for two, as = compares the array. A field that holds an array is an array even of one item: tags > 'a' fails, and tags = 'a' is false. The warning names the step that makes the sequence (the step over an array, a filter that may keep several items, *, **, $keys) and says what to write instead: an aggregate, $max(items.qty) > 1 or $sum(items.qty) + 1; a filter that tests each item, $count(items[qty > 1]) > 0; in to find a value among them, 2 in items.qty. A number filter keeps one item, so items[0].qty > 1 gets nothing, nor does a filter of an object, order[qty > 1]. = and != are warned about only where the other side is one value. The text tells the two cases apart: an operand that is always an array, such as tags, “is an array, which never equals one value”, so tags = 'a' is false for every document that follows the schema; one that is an array only for some documents, such as items.qty, “may be several values”, and passes a test with one item. For = and != the hint writes the expression again, with the other side looked for in the array: 'a' in tags for tags = 'a', and $not('a' in tags) for tags != 'a'. As != is false where a side is undefined and $not(… in …) true, that form starts with $exists of each side that may be undefined: items.qty != 2 gives $exists(items.qty) and $not(2 in items.qty). The rewrite gives the same answer wherever the operand is one value or undefined, and changes it only where it is several values;
  • with the type the result must have declared, W0212, W0213 and W0214 for a result that never has it, may have another, or may be undefined (below).

The typing does not read the guards of an expression: in $type(x) = 'number' and x > 10, with x a string in the schema, x > 10 is warned about, though the left side, always false, keeps it from running.

An expression that is the body of a step

An application may evaluate an expression against each item of an array, as the body of items.( … ): a rule on each line of an order. Declare the path of the items, and the service completes and checks the text with an item as its context, at the offsets of the text, without the application wrapping it:

#![allow(unused)]
fn main() {
let service = LanguageService::new(Some(schema)).with_context_path("items[]");
let diagnostics = service.diagnostics("price > 10 and %.customer.vip");
}

% is then the value the last step of the path was evaluated against, the order, where alone it fails with S0217; %.% is the one before, for a path of two steps such as orders[].items[]. $$ stays the document. The path is written as for Schema::shape_at; items and items[] are the same context, as a step reads the items of an array. A path the schema does not have gives an unknown context, where no field is warned about. In an editor and in jlens check, the contextPath of jlens.json declares it, or jlens check --context-path 'items[]'; in the WebAssembly and Java packages, the service’s options.

Missing fields are reported only where the context is fully known. Nothing is reported after a user-defined function, an object constructor or $lookup, so the warnings do not produce false alarms. Schemas inferred from samples can miss optional fields that the samples did not contain. Add those fields with overrides, or treat W0201 as advice.

Objects open to other fields

JSON Schema lets an object have fields its properties do not list, unless additionalProperties is false. jlens takes an object that lists its fields in properties to have those alone, and warns about another one: it is most often a typo, and the warning is what the schema is there for. An object that says it has others is not warned about: one with additionalProperties other than false (true or a schema), with patternProperties, or with no field listed at all, such as {"type": "object"}, often a map whose keys are data. An object always empty in the samples a schema is inferred from lists no field either.

additionalProperties gives such a field its type, and each pattern of patternProperties the fields whose names it matches (an ECMAScript regular expression, which may match anywhere in the name). With "additionalProperties": {"type": "number"} on totals, totals.usd + 1 gets nothing and totals.usd > 'a' gets W0208. A field the object does not list may be absent, which counts for the result’s type. Patterns alone leave the other fields unknown; with "additionalProperties": false beside them, a name no pattern matches is warned about. A name that several patterns match, or that a pattern takes too long to match, has a type that is not known, and so has a field of {"type": "object"}.

The type of the result

An application often knows the type an expression must give: the conditions of a rules engine must give a boolean. Declare it, and the diagnostics compare the result with it:

#![allow(unused)]
fn main() {
use jlens_schema::{JsonType, LanguageService};

let service = LanguageService::new(Some(schema)).with_result_type([JsonType::Boolean]);
let diagnostics = service.diagnostics("$contains(notes, 'urgent')");
// W0214: The result may be undefined, not a boolean, because of notes
}

There are three answers. The result is always one of the types, and nothing is reported. It is never one of them, W0212, as total is a number. Or it may not be: W0213 when it may have another type, with the types it may have, and W0214 when it may be undefined, pointing at the operand that makes it so. Number accepts an integer.

Most conditions are proved without a document: =, !=, in, and, or and $exists always give a boolean. An order comparison, arithmetic and most functions are undefined where an operand is, and these may be undefined:

  • a field that is not required, and what is under it: $contains(notes, 'urgent');
  • a filter, which may keep nothing: items[type = 'gift'].price > 10;
  • a step over an array that may be empty, as $sum(items.price) > 100 is when items is [] ($sum of nothing is undefined). An array with minItems of at least 1 is never empty, and inference gives minItems: 1 to an array no sample had empty;
  • a function that may give nothing, such as $lookup, $max of an empty array or $keys of an object without fields, and a condition without else.

A path over several items gives a sequence: one value alone, or several in an array. lines.price is a number for an order of one line and an array for an order of two, so a result expected to be a number gets W0213, pointing at lines; $sum(lines.price) is one number. An array constructor, [price], and functions such as $sort always give an array.

Where the typing does not know the type, nothing is reported: a function the expression defines, an object constructor, a path that binds @$v or #$i, a variable declared without a shape, a field without a schema, the parent of a step inside parentheses. LanguageService::result_type gives what it knows as a value, with no expected type: the types the result may have (None where they are not known) and the spans of the operands that may make it undefined or a sequence. ResultType::check compares it with a list of types, and answers Always, Never, Maybe or Unknown.

In an editor and in jlens check, the resultType of jlens.json declares the type for the files of a pattern, as "resultType": "boolean", or jlens check --result-type boolean; the WebAssembly and Java packages take it when a service is made, and their resultType gives the result’s type in this JSON form, with UTF-16 spans. jlens schema result prints the result’s type as JSON, with check where a type is expected:

$ jlens schema result --schema order.schema.json --result-type boolean '$contains(customer.name, "VIP")'
{
  "types": [
    "boolean"
  ],
  "undefined": {
    "start": 10,
    "end": 18
  },
  "sequence": null,
  "check": "maybe"
}

An expression with a syntax error has no answer from the command: it prints the error on standard error and ends with exit code 1, as jlens check and jlens schema uses do. The resultType of the packages does not fail: its types are not known, and the service’s diagnostics have the error.

What an expression uses of its schema

An application may store expressions written against a schema that changes. When a new version of the schema arrives, the diagnostics tell whether each expression still passes: a field that went from a boolean to a string gets W0210 under active = true. They do not tell whether something it uses changed while the expression stays valid: an enumeration that gained held leaves status = 'open' passing, and the expression may need a case for it.

LanguageService::uses answers that. It takes the fields an expression reads and gives what the schema says of each:

#![allow(unused)]
fn main() {
use jlens_core::Expression;
use jlens_schema::{LanguageService, Schema};

let service = LanguageService::new(Some(schema));
let expression = Expression::compile(r#"$sum(items[type = "book"].price)"#)?;
let uses = service.uses(&expression.reads());
let json = serde_json::to_string(&uses)?;   // kept beside the expression
}
{
  "input": {
    "$": {"types": ["object"]},
    "items": {"types": ["array"], "required": true},
    "items[]": {"types": ["object"]},
    "items[].price": {"whole": true, "types": ["number"], "required": false},
    "items[].type": {"whole": true, "types": ["string"], "enum": ["book", "toy"],
                     "closed": true, "required": true}
  },
  "bindings": {}
}

input holds the paths read of the input, and bindings those of each variable, by name; input is left out when the expression does not read its input. A path is written as the overrides write it: $ is the value itself, [] steps into the items of an array, and a name that is not a plain one is written between backquotes, as in an expression (customer.`odd name` ). Schema::shape_at reads every path of an answer, but a name that itself holds a backquote. Every value on the way to a field has its own path, and so do the items of an array.

What the schema says of a path:

MemberMeaning
typesThe types the schema gives the value, as JSON Schema names them; left out when it gives none
enumThe values it lists
closedtrue when the enumeration is declared and has no open domain, so that a value outside it is warned about (W0206); left out for one inferred from samples
domainIts open domain
formatIts string format
requiredWhether the object that holds the field requires it. Left out for $ and for the items of an array. A field is always there only when the fields on its way are required too
wholetrue when the expression reads the value whole, not only some of its fields
unknowntrue when the schema says nothing there: the value has no schema, or the field is not one it declares

The paths are those of the analysis of the reads, which is an upper bound. Where it follows a value, they are the fields the expression names, those of a predicate included. Where it does not (*, **, $eval, a value given to a host function), the value is read whole, and every path the schema has under it is listed. $eval can also read any variable: the answer then has "everyBinding": true, and every variable declared with a schema, whole. The host functions declared to the service are not values, and are left out of bindings.

The call of a function that is not built in reads the context of its call whole, as a host function written in Rust can read it: $describe(items[0]) at the top of an expression uses the whole input, and every change of the schema is then a change for the expression. The host functions of the WebAssembly, Python and Java packages receive their arguments and nothing else, and so do those marked HostFunction::without_input in Rust. LanguageService::uses_of takes the expression itself, and counts a call to a function declared to the service (with_function) as reading its arguments alone, and the context that a - of its signature may take: the call above uses items, whole, and nothing else.

#![allow(unused)]
fn main() {
let uses = service.uses_of(&expression);
}

Give uses the reads when a declared function reads its context, or when the application knows better which functions do (Expression::reads_with).

Under a value read whole, a recursive schema is listed down to where it repeats: what is under a definition is listed once, at the place nearest to the value read whole, and another value of that definition is the last path on its way. Read whole, a tree whose children are the document itself gives $, its fields, children and children[]. A change inside the definition shows in the paths listed.

The answer depends on nothing else in the schema, and its paths and names are written in order: two schemas that give an expression the same text differ in nothing it uses.

What changed between two schemas

When the answers differ, Uses::changes tells where. It compares the answer kept beside the expression with that of the new schema:

#![allow(unused)]
fn main() {
let old: Uses = serde_json::from_str(&kept)?;
let new = LanguageService::new(Some(new_schema)).uses(&expression.reads());
let changes = old.changes(&new);
if !changes.is_empty() {
    let json = serde_json::to_string(&changes)?;   // shown to who reviews the expression
}
}

With price now an integer or a string, type no longer required and with one more value, and a field weight added to the items, an expression that reads the items whole (items[type = "book"]) gets:

{
  "input": {
    "added": {
      "items[].weight": {"types": ["number"], "required": false}
    },
    "changed": {
      "items[].price": {"types": {"old": ["number"], "new": ["integer", "string"]}},
      "items[].type": {
        "enum": {"old": ["book", "toy"], "new": ["book", "game", "toy"], "added": ["game"]},
        "required": {"old": true, "new": false}
      }
    }
  }
}

input and bindings, by variable, hold the changes as the answers hold the paths, and each is left out when nothing changed there: {} means that nothing the expression uses changed.

MemberMeaning
addedThe paths that only the new answer has, with what the new schema says of each: a field added under a value the expression reads whole
removedThe paths that only the old answer has, with what the old schema said: a field removed under a value read whole
changedThe paths of both answers of which the schemas do not say the same. Each has the members that changed, under their names in the answer, as {"old": …, "new": …}; a side on which the member was left out is left out here too

A field that the expression names stays in the answer when the new schema drops it. It is then under changed, with "unknown": {"old": false, "new": true} and what the old schema said of it. A path is compared with the same path, so a field that was renamed is one path that became unknown, or was removed, and another that was added.

The types and the values of an enumeration are compared as sets: their order is not a change. An enumeration that changed also has added and removed, the values that only one side lists, so that an application can tell a value that was added, which leaves the expression’s comparisons as they were, from one that was removed.

In the CLI and the other packages

Every place that has the schema gives the two answers, as the same JSON:

WhereWhat an expression usesWhat changed
RustLanguageService::uses(&reads), uses_of(&expression)Uses::changes(&new)
CLIjlens schema uses <EXPR>jlens schema changes OLD NEW
WebAssemblyservice.uses(expression.reads(bindings))usesChanges(old, current)
Javaservice.uses(expression)uses.changes(current)

The comparison takes the two answers and nothing else, so the answer kept beside an expression is compared when its schema is gone. In Rust, Uses::from_json reads an answer kept as JSON; it refuses what is not in the form above, where the derived Deserialize would take an array for an object.

jlens schema uses prints the answer of an expression, given as an argument or with -f. It takes its schema, variables and host functions as jlens check does: from --schema, and from the jlens.json of the current directory or of --config, which --path applies to an expression given as an argument. A host function the configuration declares reads its arguments alone, as uses_of takes it. jlens schema changes compares two files it wrote:

jlens schema uses -f rules/books.jsonata --schema order-v1.schema.json > books.uses.json
jlens schema uses -f rules/books.jsonata --schema order-v2.schema.json > books.new.json
jlens schema changes books.uses.json books.new.json
input
  added    items[].weight: number, optional
  changed  items[].price: types number -> integer | string
  changed  items[].type: enum added "game"; required true -> false

It prints no change when nothing the expression uses changed, and with --json the JSON form, {} then. Both commands exit with 0 whether something changed or not; a file that is not an answer is a usage problem, 2.

The fields of a schema

An application that builds its own list of attributes from a schema, as a rules editor does for its menus, or that matches the fields of two versions of a schema to see which moved, needs each field with what jlens knows of it. Schema::fields lists them, so that the application does not walk the schema itself, through its $refs, branches and tuples:

#![allow(unused)]
fn main() {
use jlens_schema::Schema;

let schema = Schema::from_json_schema(&serde_json::json!({
    "type": "object",
    "required": ["status"],
    "properties": {
        "status": {"type": "string", "title": "Status", "enum": ["open", "closed"],
                   "x-attribute-id": "A17"},
        "lines": {"type": "array", "items": {"type": "object", "properties": {
            "sku": {"type": "string", "x-jlens-domain": "products"}}}},
        "internal": {"type": "string", "x-jlens-hidden": true}
    }
}))?;
let fields = schema.fields();
}
[
  {"path": "$", "typeSummary": "object", "types": ["object"]},
  {"path": "lines", "typeSummary": "array<object>", "types": ["array"], "required": false},
  {"path": "lines[]", "typeSummary": "object", "types": ["object"]},
  {"path": "lines[].sku", "typeSummary": "string", "types": ["string"], "required": false,
   "domain": "products"},
  {"path": "status", "typeSummary": "string", "types": ["string"], "required": true,
   "label": "Status", "enum": ["open", "closed"], "closed": true,
   "extensions": {"x-attribute-id": "A17"}}
]

Each entry tells what completion and hover tell of its path:

  • path, written as the answers of uses write it, and in their order: $ is the value itself, [] the items of an array. A recursive schema is listed down to where it repeats, as uses lists a value read whole.
  • typeSummary, the types as completion shows them, and types, as JSON Schema names them; unknown and no types where the schema says nothing, as under a $ref that was not followed.
  • required, for a field only, wherever the schema says it (the keywords jlens reads); label (title) and description; enum, with closed when a value outside it is warned about; domain and format.
  • extensions: the field’s own x- keywords, as written, which jlens keeps and does not read, such as a key that the application gives each field and that stays the same when the field is renamed. Those of a $ref’s place come before those of its target. A schema written back by to_json_schema keeps them.

The overrides applied to the schema are in the list, and a hidden field is left out with what is under it, as completion leaves it out. LanguageService::fields lists the fields of the schema of the service’s input; the WebAssembly and Java packages call it service.fields(), with the same JSON.

Fields renamed by a new version

When a new version of a schema renames fields, the expressions written against the old one still name the old fields. LanguageService::rename rewrites them: given a table of paths, each old path to its new one, it replaces each step that reads a renamed field, found as uses finds the fields an expression reads, and keeps the rest of the text as written. A rule migrated to a new version takes four steps: what changed, the table, the rename and the check.

#![allow(unused)]
fn main() {
use std::collections::{BTreeMap, HashMap};

use jlens_core::Expression;
use jlens_schema::{LanguageService, ListedField};

// Two versions of the schema of an order, each field with a key of the application's:
// `lines` became `items`, and `qty` `quantity`.
let before = LanguageService::new(Some(version_1));
let after = LanguageService::new(Some(version_2));
let rule = Expression::compile("status = 'open' and $sum(lines.(qty * price)) > 100")?;

// 1. Does the rule use anything the new version changed? `lines` and `qty` are gone.
let changes = before.uses_of(&rule).changes(&after.uses_of(&rule));
assert!(changes.input.removed.contains_key("lines[].qty"));

// 2. The table: each old path to the new one with the same key.
let key = |field: &ListedField| field.extensions.get("x-attribute-id").cloned();
let new_paths: HashMap<_, _> = after.fields().into_iter()
    .filter_map(|field| Some((key(&field)?.to_string(), field.path)))
    .collect();
let table: BTreeMap<String, String> = before.fields().into_iter()
    .filter_map(|field| Some((field.path.clone(), new_paths.get(&key(&field)?.to_string())?.clone())))
    .collect();

// 3. The rename.
let renamed = before.rename(&rule, &table)?;
assert_eq!(renamed.text, "status = 'open' and $sum(items.(quantity * price)) > 100");
assert!(renamed.unsure.is_empty());

// 4. The rewritten rule uses nothing the new version does not have.
let migrated = Expression::compile(&renamed.text)?;
assert!(after.uses_of(&migrated).input.iter().flatten().all(|(_, used)| !used.unknown));
}

A step is renamed where it reads the field, whatever the path that leads there: a relative path in a predicate, a parent kept in a variable ($o := order; $o.total), the parent of %, a step written as a string (customer."name"). The same name under another parent, or of an object the expression builds, is left alone. A new name that is not a plain one is written between backquotes, and so is one the text beside it would run into (`a`and b with a renamed x gives `x`and b). An entry renames the last name of its path. A field under a renamed parent follows it without an entry of its own, and an entry for it gives it under the new parent (lines[].qty to items[].quantity), as a table built from the two versions’ fields does; an entry that moves a field to another parent fails, and so do a field renamed twice, two fields renamed to the same path, a path with a backquote that opens or closes no name or a dot with no name before it (a..b), and a name that holds a backquote, which JSONata cannot write.

The answer gives the rewritten text, each edit with its span, and the places the rename cannot be sure of, in unsure, where it leaves the text as written for someone to look at:

reasonThe place
wholeA value that holds a renamed field is used whole: given to a function that may read the field or its name ($keys(customer), $sift, $string, a function of the expression’s own or a host function the service does not declare), iterated by * or **, an operand. path is the value
stringA renamed field named by a string given to $lookup, as in $lookup(customer, 'vip')
mixedA step that reads a renamed field and another one, which keeps its name: (x ? a : b).name with a.name renamed alone, or (x ? a : $sift(b, $f)).name, where the other is a field of an object the expression builds or a function gives (a group-by, $spread, a function of the expression’s)
lostThe analysis gave up on part of the expression, as for $eval: a renamed field may be read anywhere

The result of the expression is not listed: an expression that returns an object holding a renamed field returns it with its new name. Only the fields of the input are renamed, not those of variables. The WebAssembly and Java packages call it service.rename(...), with the spans in UTF-16 code units.

Editors (language server)

jlens lsp is a language server: editors that speak the Language Server Protocol get, in JSONata files:

  • completion of fields, variables, and built-in and host functions;
  • diagnostics: syntax errors, annotation problems, and fields that the schema does not have, with a “did you mean”;
  • hover, with the type and description of fields and the documentation of functions;
  • signature help in function calls.

It is the language service of the web editor, behind a standard protocol. Install it with the CLI:

cargo install jlens-cli
jlens lsp          # what editors run; it speaks LSP on standard input and output

Configuration: jlens.json

A jlens.json at the root of a workspace folder says which schema, variables and host functions apply to which expression files, and what their expressions must give:

{
  "rules/**/*.jsonata": {
    "schema": "schemas/order.schema.json",
    "variables": {"minimum": {"type": "number"}, "region": null},
    "functions": [
      {"name": "shipping", "signature": "<ns:n>", "params": ["weight", "region"],
       "summary": "Shipping cost of a weight to a region"}
    ]
  },
  "conditions/*.jsonata": {"schema": "schemas/order.schema.json", "resultType": "boolean"},
  "**/*.jsonata": {}
}
  • Keys are glob patterns, matched against the file’s path relative to the folder of jlens.json. * stays within a directory and ** crosses directories. The first matching pattern applies; files that no pattern matches get completion and diagnostics without a schema.
  • schema is a JSON Schema of the input documents, relative to the folder of jlens.json. jlens schema infer creates one from sample documents; see the schema guide. Its $refs to other files are followed when the files are at the same relative paths from the schema’s; nothing is read from the network, and a $ref that is not followed is shown as a message and leaves its place unchecked (A schema in several documents).
  • variables declares the variables the expressions are evaluated with, with a JSON Schema of each value, or null when the shape is unknown. Names can start with $. A $ref to a file there is relative to the folder of jlens.json.
  • functions declares the host functions: name, and optionally signature, params and summary.
  • resultType is the JSON type the result of an expression must have, or an array of them (["number", "null"]), as the conditions of a rules engine must give a boolean. A result that never has one is warned about (W0212), as is one that may have another type (W0213) or be undefined (W0214); see The type of the result.
  • contextPath is a path, such as items[], for expressions that run as the body of its steps, as a rule on each line of an order runs inside items.( … ): they are completed and checked with an item as their context, and % is the order (An expression that is the body of a step).

All settings are optional. When jlens.json or a JSON file changes, the server reloads the configuration and the schemas, and checks the open files again. It relies on the editor’s file watching, or on the file being saved in the editor. A configuration that cannot be read is reported as a message, and its files are checked without settings.

The client can also pass the same object as initializationOptions, relative to the first workspace folder. Its patterns come before those of jlens.json.

jlens check reads the same file, so that CI reports what the editor shows.

Neovim

With Neovim 0.11 or later, in init.lua:

vim.filetype.add({ extension = { jsonata = "jsonata" } })
vim.lsp.config("jlens", {
  cmd = { "jlens", "lsp" },
  filetypes = { "jsonata" },
  root_markers = { "jlens.json", ".git" },
})
vim.lsp.enable("jlens")

Helix

In languages.toml:

[[language]]
name = "jsonata"
scope = "source.jsonata"
file-types = ["jsonata"]
roots = ["jlens.json"]
language-servers = ["jlens"]

[language-server.jlens]
command = "jlens"
args = ["lsp"]

Emacs

With Eglot (built into Emacs 29):

(define-derived-mode jsonata-mode prog-mode "JSONata")
(add-to-list 'auto-mode-alist '("\.jsonata\'" . jsonata-mode))
(with-eval-after-load 'eglot
  (add-to-list 'eglot-server-programs '(jsonata-mode "jlens" "lsp")))

Visual Studio Code

The jlens extension (thkprado.jlens, from 0.15) highlights JSONata and starts jlens lsp for the jsonata language, in files ending in .jsonata. It looks for the server in this order:

  1. the setting jlens.server.path, the path of a jlens program;
  2. the jlens binary bundled with the extension, in its packages for Linux, macOS and Windows on x86-64, and Linux and macOS on ARM64;
  3. jlens on the PATH, on other platforms.

When it finds none, it says so, and highlighting keeps working. jlens.server.path is read from user settings only, never from a workspace’s: a repository cannot choose which program runs. The command jlens: Restart Language Server starts the server again, after an update of jlens for example, and changing the setting does too.

The jlens output channel shows the server’s version and path, and its messages. The setting jlens.trace.server (messages or verbose) adds the protocol’s messages to it.

The extension also checks jlens.json as it is edited, with a JSON Schema: unknown settings, misspelled ones and wrong types are underlined, and hovers describe each setting.

If another JSONata extension is installed, VS Code uses both: disable the other’s language features, or you get the diagnostics of both. In the browser, the WebAssembly package offers the same service to CodeMirror and Monaco.

Positions

The server counts positions in UTF-16 code units, the protocol’s default, or in bytes when the client offers UTF-8 (general.positionEncodings). Documents are synchronized incrementally. Positions past the end of a line or of the document are clamped to it, as the protocol requires.

Errors

A bug in jlens that panics while the server handles a request does not stop the server: the request is answered with an InternalError, and a panic while it handles a notification (such as checking a document after a change) is logged with window/logMessage. The panic itself is printed on the standard error, which editors keep in the server’s log. Please report it, with the text of the document.

Architecture overview

                ┌───────────────────────── jlens-core ──────────────────────────┐
source ──► lexer ──► Pratt parser ──► raw tree ──► process ──► Ast (Expression)  │
                │      (recover mode, annotations)    (paths, stages, %,         │
                │                                      tail calls)       │      │
                │                                                        ▼      │
input JSON ──► Value / Document ───────────────────────────────────► evaluator  │
                │                                    function library ──┘  │    │
                │                                    Tracer events ◄───────┘    │
                │                                       │                       │
                │                     AuditCollector ◄──┴──► JsonlTracer, ...   │
                └──────────────────────────┬───────────────────────────────────┘
                                           │ result, AuditTree, Explanation
        jlens-schema: Schema (inference, JSON Schema) ─► typing ─► LanguageService
        jlens-cli: the `jlens` binary        jlens-wasm: the ES module for browsers

Crates

CrateContentsDepends on
jlens-coreLexer, parser, syntax tree, evaluator, function library, errors, audit subsystemserde_json, indexmap, jlens-regress (a fork of regress), ryu-js
jlens-schemaStructural metadata (Schema), inference, JSON Schema import and export, static typing of expressions, the language servicejlens-core
jlens-cliThe jlens command: eval, check, functions, schema, astjlens-core, jlens-schema, clap
jlens-wasmWebAssembly bindings: Expression, Document, LanguageService, … with TypeScript declarationsjlens-core, jlens-schema, wasm-bindgen
xtaskRepository automation: conformance, generated docs, doc checks, the Wasm packagejlens-core

The core crate has no dependency on the others. Everything a tool needs from the language is public there:

  • the syntax tree, with node ids and spans;
  • recovering parsing;
  • the function catalog;
  • the tracer events.

From source to result

  1. Lexing and parsing (Parsing). The lexer produces tokens with byte spans and collects documentation comments. A Pratt parser, ported from jsonata-js, builds a raw tree. In recover mode it records errors and keeps going, which editors need. Annotations are attached to the subexpression that follows them.
  2. Processing. The raw tree becomes the Ast:
    • path steps and their stages (filters, sorting, #, @) are laid out;
    • parent references (%) are resolved to ancestor slots;
    • tail calls are marked. The result is immutable and shared by all evaluations of the expression.
  3. Evaluation (Evaluation). A tree-walking interpreter over the Value model. Values are reference counted, with sequences flagged as in jsonata-js; see ADR 0003. Functions are values. Tail calls run in a trampoline. Guardrails bound the depth and the time.
  4. Tracing. When a tracer is attached, the evaluator reports events: entering and leaving a node, operands, short circuits, branches, bindings and filters. The audit collector turns them into an AuditTree, and explain summarizes the tree. See ADR 0004.

Tooling

jlens-schema builds on recovering parsing (Schema and language service):

  • Schema records the shape of sample documents and round-trips through JSON Schema.
  • The typing walker follows an expression the way the evaluator would. It computes what each part of the expression refers to in the schema: paths, filters, variables and function results.
  • The LanguageService answers completion, diagnostics, hover and signature help from that information. A placeholder is substituted at the cursor so that incomplete expressions parse.

The CLI and the WebAssembly package are thin layers over these crates. The WebAssembly package converts offsets between UTF-8 bytes (Rust) and UTF-16 code units (JavaScript) at the boundary.

Quality

  • Conformance testing: the official JSONata test suite runs on every cargo test, against a baseline that may only improve. Property tests check that nothing panics.
  • Performance: criterion benchmarks and a comparison with jsonata-js.
  • Documentation checks: cargo xtask doc-check runs every example in this book. The generated pages (functions, errors) are checked against the code.

The design decisions are recorded in the decision records.

Parsing

Parsing turns source text into the tree the evaluator walks. It has three stages, each ported from src/parser.js in jsonata-js:

source ──► lexer ──tokens──► Pratt parser ──raw tree──► process ──► Ast
            (lexer.rs)         (parser.rs)               (process.rs)  (ast.rs)
Entry pointBehaviour
jlens_core::parse(src)Stops at the first error and returns it
jlens_core::parse_recover(src)Never fails. Errors become Error nodes plus diagnostics
Expression::compile(src)parse, then wraps the tree for evaluation
jlens_core::debug::{tokens, raw_tree}Inspection, used by jlens ast --tokens/--raw

Lexer

The lexer produces one token at a time, on demand, because one character is ambiguous: / starts a regular expression in operand position (/ab+c/i) and means division in operator position (a / b). The parser passes an infix flag with each request.

Token kinds are names, variables ($x), strings, numbers, the literals true, false and null, regexes and operators. and, or and in are lexed as operators; the parser turns them back into names when they appear where an operand is expected, as in and.or.

Differences from the reference lexer:

  • Spans. Every token records its full byte range. The reference implementation only records the position just after a token.
  • Doc-comments. /** ... */ comments are kept and attached to the next token, for annotations. Ordinary comments are skipped as before.
  • Surrogates. 𝄞-style escape pairs are combined into one character. A lone surrogate becomes U+FFFD, because Rust strings cannot hold one.

Pratt parser

JSONata’s grammar is mostly operators, and a Pratt parser (top-down operator precedence) handles it with a table of binding powers:

Binding powerOperators
80[ (filter), ( (call), @, #
75.
70{ (group-by), unary - operand
60* / %
50+ - &
40= != < <= > >= in ^ ~> ?: ??
30and
25or
20?
10:=

Each token can define two parse functions:

  • nud, which parses the token in prefix position, such as a literal, -x, (block), [array] or {object};
  • led, which parses it in infix position, such as a + b, a[...], f(...) or a{...}.

The core loop is short:

expression(rbp):
    t = current token; advance
    left = t.nud()
    while rbp < binding power of current token:
        t = current token; advance
        left = t.led(left)
    return left

A few constructs are desugared while parsing:

  • x ?? y and x ?: y become a fallback node (NodeKind::Fallback) that evaluates x once, then keeps its value if it exists (??) or is true as a Boolean (?:). jsonata-js desugars them into the conditions $exists(x) ? x : y and x ? x : y, with a copy of x: nesting them doubles the tree at each level;
  • function($a){...} is recognised as a lambda when the callee of a call is the name function or λ.

Annotations and binding power

When the first token of an expression carries a doc-comment, the loop above runs in two phases. First it parses with binding power max(rbp, 30), which stops at and or or, and attaches the annotation to that result. Then it continues with the original rbp. Pratt parsing builds the same tree regardless of where the loop is split, so the annotation marks a subtree without changing the shape of the tree. The test annotations_never_change_the_tree checks this property.

Post-processing

process.rs is the port of processAST. It turns the raw tree into the evaluator’s tree:

  • Paths. Nested . operators become one Path node with a flat list of steps. String steps become names, and number or boolean steps are rejected (S0213).
  • Predicates. step[expr] becomes a filter stage on the step. On a non-path expression such as $var[0], it becomes a predicate that applies to the whole result.
  • Bindings and clauses. @$v and #$i set focus and index on the step and switch it to tuple mode. ^(...) becomes a Sort step, and {...} after a step becomes its group.
  • The parent operator %. Each % gets an ancestor slot. The processor walks back through the enclosing path to the step whose input is the wanted ancestor, and marks it to bind that slot’s label (!0, !1, …). That step and the steps after it run as a tuple stream. Slots live in Ast::slots, an arena, because the reference implementation shares and mutates slot objects across nodes.
  • Tail calls. A function call in tail position of a lambda (either branch of a conditional, or the last expression of a block) is wrapped in a thunk. The evaluator’s trampoline runs thunks in a loop, so tail-recursive functions don’t grow the stack. A call with a predicate or a group-by is not wrapped: the trampoline makes the call alone, which would drop them.

Finally, nodes receive sequential NodeIds in pre-order. Audit trees will refer to nodes by these ids.

Error recovery

In recover mode, an error does not abort parsing. The behaviour follows jsonata-js:

  • the error is recorded;
  • the rest of the input is consumed;
  • the current token becomes an error marker with binding power 10, which wraps whatever was parsed before it.

So Account.Order[0;].Product yields path(Account, Order[0]) plus error S0202.

jlens recovers in more cases than jsonata-js:

  • Lexer errors, such as an unterminated string while the user is typing, are recovered.
  • Post-processing errors (S0209, S0210, S0213, S0215–S0217) become diagnostics and error nodes.
  • An expression that starts at the error marker reuses the recorded error, instead of reporting an extra S0211 for an undefined token.

The seven recovery cases from jsonata-js’s test/parser-recovery.js are ported in crates/jlens-core/tests/parser.rs. They check the same error codes, positions and partial trees. The same test file also parses every expression of the official suite: all valid expressions must parse, and all invalid ones must fail with the expected S0xxx code.

Evaluation

The evaluator (crates/jlens-core/src/eval.rs) is a tree-walking interpreter over the processed syntax tree. It is a function-by-function port of src/jsonata.js in jsonata-js. That code effectively defines JSONata’s subtler behaviour, such as when a result is a sequence or an array, so jlens keeps its structure recognisable. Unlike jsonata-js, evaluation is synchronous.

Expression::evaluate(input, bindings)
  └─ eval::evaluate          converts input JSON, wraps an input array, binds $$ and bindings
       └─ Evaluator::eval    one call per node: dispatch, predicates, group-by, sequence unwrapping
            ├─ path / step / tuple_step / filter / stages      location paths
            ├─ binary / array_constructor / group / sort       operators and constructors
            └─ call / apply / partial / apply_expression       functions

Values

See ADR 0003 for the reasoning. The short version:

ValueNotes
UndefinedNever escapes the API: results become Option<serde_json::Value>
Null, Bool, Number(f64), String(Rc<str>)Numbers are IEEE doubles, as in JavaScript
Array(Rc<Array>)Items plus flags: SEQUENCE, KEEP_SINGLETON, OUTER_WRAPPER, CONS, TUPLE_STREAM
Object(Rc<RefCell<Map>>)Insertion-ordered. Shared and mutable because transforms update matches in place
Function(Rc<Function>)A lambda closure, a built-in, a host function, a partial application, a transformer, or a regex

Sequences

A sequence is the result of navigating a path. After evaluating any node, a sequence of length 0 becomes undefined, and a sequence of length 1 becomes its only item, unless KEEP_SINGLETON is set by the [] modifier. Arrays that come from the input, and arrays built with [...], are not sequences, so they never collapse. This single rule, applied at the end of Evaluator::eval, is why Account.Order.Product.Price returns a number for one product and an array for several.

When the input document is itself an array, it is wrapped in a one-item sequence flagged OUTER_WRAPPER, so that the array counts as a single context value. $ unwraps it again.

Paths and tuple streams

path evaluates its steps left to right. Each step maps over the current sequence and flattens the results by one level. Array constructors flagged CONS are not flattened.

Steps that bind variables switch the path into tuple-stream mode from that step on. These are @$focus, #$index, and steps marked as the ancestor for a %. In this mode each item is carried as a tuple, an object holding @ (the current value) and the bound variables. Later steps, predicates, sort keys and group-by expressions are evaluated in a frame created from the tuple. At the end of the path the tuples are mapped back to their @ values, unless an enclosing path still needs the ancestry.

Functions and the trampoline

A lambda value captures its definition (Arc<LambdaDef>, shared with the tree), the environment frame in which it was created, and the context value. Applying it:

  1. validates the arguments against the lambda’s signature, if it has one;
  2. creates a child frame of the captured environment and binds the parameters (missing ones are bound to undefined, so they shadow outer variables);
  3. evaluates the body.

When post-processing marked a call as being in tail position, the body evaluates to a thunk instead of making the call. Evaluator::apply runs thunks in a loop, so tail-recursive functions run in constant stack depth. $loop(100000, 0) in the test suite exercises this.

Built-in functions are Native entries in functions/mod.rs, each with its signature and declared parameters. Host functions (HostFunction, from the bindings) have an optional signature and an arity; their arguments and results are converted to and from JSON (ADR 0006). Partial application ($f(?, 2)) works for lambdas, built-ins and host functions.

Signature validation

Signatures such as <s-nn?:s> are checked by turning the arguments into a string of type symbols (s, n, b, l, a, o, f, or m for undefined). That string is matched against the parameter patterns by a small greedy backtracking matcher. The matcher is equivalent to the regular expression jsonata-js builds, but needs no regex engine. The match then:

  • fills in the context value for - parameters (T0411 if its type is wrong);
  • wraps single values for a parameters;
  • checks array subtypes (T0412).

Environments and memory

Frames form a chain from the innermost scope to the root; the built-ins sit behind the root. A closure stored in the frame that it captured creates a reference cycle, as in $f := function(){ $f() }. Reference counting cannot reclaim such a cycle on its own. The evaluator therefore records every frame that a variable binding (:=) gives a function, array or object, and clears those frames when the evaluation ends. The frame of a call or of a tuple is not recorded for its arguments or fields: they existed before it, so none can reach it, and it goes back to the evaluator for the next call or tuple once its scope ends. A value only gains a reference later when a transform stores into an object, and every cycle such a store closes passes through that object. A closure reaches it by its input, since the update runs with the object as input, or through a frame, so a transform that stores something holding a function records the object, and the evaluator clears its fields when the evaluation ends, after the result is written.

Guardrails

LimitOptionErrorDefault
Evaluation depthOptions::max_depthD101150,000 native, 500 in Wasm
Wall-clock timeOptions::timeoutD1012none
Steps: nodes evaluated, functions called back, and 1,024 steps of regular expression backtracking each (ADR 0018)Options::max_stepsU1006none
Cancellation from another threadOptions::cancel_tokenU1003none
Expression nesting(fixed)U10011,000 levels of syntax tree, checked by the parser
Value nesting(fixed)U10011,000 levels of arrays and objects, checked where a value is converted to JSON, compared or serialized
Length of a built stringOptions::max_string_lengthU1001256 MiB (in bytes of UTF-8)
Items of a built arrayOptions::max_array_lengthU100116,777,216
Size of the result, and of the arguments of a host functionOptions::max_result_sizeU1001256 MiB (in bytes of compact JSON)

jsonata-js has no depth limit of its own; it stops when the JavaScript stack overflows. jlens needs limits so that it fails with an error instead of crashing the process.

  • Native targets. The parser, the post-processing pass, the evaluator and the schema typing walker grow their stack on demand (with the stacker crate), so the default depth limit is generous. The CLI also runs on a thread with a 64 MiB stack, which covers the other recursive walks of the tree (printing it as JSON, for example).
  • WebAssembly. The stack cannot grow, and an overflow traps, which leaves the module instance unusable. jlens links the module with a 4 MiB stack and checks the space left before each recursive step (jlens_core::stack), failing with D1011 (evaluation) or U1001 (parsing) instead. WebAssembly frames also use the JavaScript engine’s own stack, which is about 1 MiB in V8 and cannot be measured from inside the module; the lower default depth limit (500) keeps evaluations inside it. The WebAssembly guide has the measurements behind it. A larger maxDepth can raise a JavaScript RangeError and break the instance.
  • Calls from native functions. A lambda whose body is a tail call leaves no expression on the stack, so a recursion through a higher-order function (function($n){ $map([$n], function($v){ $f($v) }) }) deepens only through the native function’s calls back. Each of those calls counts as a level of depth and checks the stack too.

The nesting limit bounds every recursive walk of the syntax tree, including the ones that do not grow the stack, such as cloning and dropping it. Both nested subexpressions and the operators of a chain count: 1 + 2 + 3 is a tree two levels deep, built by a loop rather than by recursion. 1,000 levels is far more than any hand-written expression uses.

Values can nest much deeper than expressions: an input read from a Source (or from JavaScript in Wasm) has no depth limit, and a tail-recursive function can wrap a value in an object at each of its steps, without deepening the evaluation. So the walks over values are bounded in three ways:

  • Walks that only enter arrays (**’s and *’s flattening, field lookups across nested arrays, $boolean, $keys, $spread) keep their own stack, and walk any depth.
  • Walks that enter objects too fail with U1001 beyond 1,000 levels of arrays and objects: converting the result or a host function’s arguments to JSON, = and $distinct, **, $string and $clone. They also grow the stack natively. The limit protects the caller as well: the JSON returned is dropped and printed by recursive code (serde_json), and in Wasm the walks run on the JavaScript engine’s stack. jsonata-js works at 2,000 levels and raises a RangeError before 5,000. Audits truncate the values they capture at the same depth.
  • Dropping counts how deep the drops of arrays and objects nest. Past 100 levels, the arrays and objects that only the dropped one holds are emptied from a list, instead of each inside the drop of its parent. Those that hold no array or object of their own, most of them, skip the count.
  • Recursive walks grow the stack natively every 16 levels rather than at each value.

The size limits stop an expression that doubles a string or an array on each step, or a path whose steps multiply the length of a sequence, before it runs out of memory, which would abort the process. They are checked by the operators that build strings and arrays (&, ranges, array constructors, path steps) and on the value that each built-in or host function returns; $join checks the length before joining. The operators check before they build the value; a function’s result is checked once it has returned. * and **, which flatten nested arrays, count the items as they go.

The string and array limits apply to each string and array on its own, and values are shared rather than copied: an object bound to a variable can be nested in a new object twice, then that object twice, and so on. Thirty such steps stand for about a billion copies of the first object while using little memory, until something writes them all out. So everything that writes a value out is limited too:

  • The result, which becomes JSON when the evaluation ends, is measured as it is converted: its size is the length of its compact JSON text, counting a shared value each time it appears. The conversion stops once the size passes Options::max_result_size, and the evaluation fails with U1001. Escaped characters count as one byte, so the size is slightly below the length of the text that format_json prints.
  • The arguments of a host function are measured together in the same way, and so is its context value (HostCall::input).
  • $string and & write JSON text, which is a string: the text is checked against Options::max_string_length as it is written. $clone (and the transform operator, which clones its input) gives the values jsonata-js gets by writing that text and parsing it, but copies the value without the text; it counts the length the text would have, and fails where $string would.
  • Functions whose result can be many times their input check the limits while they build it, so that they stop at the limit instead of building past it: $replace (a long replacement, or many $0s, for each match), $split and $match (a part or a match per character), $pad, $join and $fromMillis (a marker writes up to 100 characters). So does a filter whose predicate gives a position many times, which selects its item as many times ([0..9][($i := $; [1..20].$i)] is 200 items).
  • The value of an error (T2001, T0410 and others) is left out when it is larger than the default size of a result.

Tracing hooks

The evaluator reports its work to an optional Tracer; ADR 0004 records why. The hooks sit at these points:

HookWhere
enter / exitEvaluator::eval, around every node, including errors
operandsbinary, before a comparison or in
short_circuitbinary, when and/or skips its right side
branchthe conditional, after the condition
bind:=, before binding
filter_begin / filter_item / filter_endfilter, around expression predicates (numeric indexes are not reported)

When no tracer is attached, eval calls the untraced code directly. The traced variant is a separate function marked cold, so the hot path does not change. The audit guide describes the tracers built on these hooks.

Schema inference and the language service

The jlens-schema crate has four modules:

ModuleRole
shape.rsThe Shape model, incremental inference, overrides
jsonschema.rsConversion to and from JSON Schema 2020-12
typing.rsStatic typing of expressions against shapes
service.rsCompletion, diagnostics, hover and signature help

Inference

A Shape describes all the values found at one place in the documents. Shape::observe folds one more value into it:

  • Types. Each value adds its JSON type. A number written without a fraction is an integer; one with a fraction or an exponent turns the shape into number. The float_roundtrip feature of serde_json preserves that distinction.
  • Objects. Every field gets a sub-shape, and every object observed increments a counter. required is field observations == objects observed, and presence is the ratio of the two.
  • Arrays. All items of all arrays observed here fold into one items shape.
  • Scalars:
    • numbers update the minimum and the maximum;
    • strings narrow a common format;
    • up to ten distinct scalar values are tracked. They become an enumeration once at least two distinct values exist and some value repeats, which keeps unique identifiers out of enumerations.

Inference never looks back at earlier samples, so Schema::observe can process a stream of documents in constant memory per distinct field.

Static typing

A type Ty is a set of shapes plus a partial flag. The flag means that something unknown contributed: a user function, an object constructor, or a missing schema. A shape that refers to definitions of its schema, as the recursive $refs of a JSON Schema do (ADR 0024), is replaced in the set by the shapes it stands for when a type is made of it, so each shape of a type is read with the definitions of its schema, and a walk over every shape below (**) visits each once. Walker::walk computes the type of each node and applies the evaluator’s context rules:

  • A path evaluates each step against the elements of the previous step’s result. Elements are the shapes with arrays replaced by their items, recursively, which is the flattening the evaluator applies.
  • Stages of a step (predicates and index bindings) see the step’s elements. A group-by sees the elements of the path’s result.
  • @$var binds the step’s elements and leaves the context unchanged. #$i binds a number.
  • $x := e binds x to the type of e until the end of the enclosing block.
  • Lambdas are walked with their parameters bound to unknown types. When a lambda is the callback of $map, $filter, $single, $sort or $reduce, its parameters get the element type of the array argument.
  • Calls to built-ins that return their first argument ($sort, $filter, $reverse, $distinct, $shuffle, $single, $clone, $sift) keep its type. $append returns the union of its arguments’ types. Other built-ins return scalars, except those whose structure is opaque, such as $map and $lookup, which return unknown types. A name bound outside the expression (a declared variable or host function) is not a built-in, and its calls return unknown types.

A type also tells whether its value may be undefined, by the span of the operand that makes it so; nothing is warned by this alone. The context a node is walked against is always there, as each item of a path is. A field step is undefined where the objects may lack the field (it is not required), an item may not be an object, or the value it steps over may be an empty array; * and ** likewise. A path is undefined where one of its steps is, a filter may keep nothing, or a step before the last gives an array, which may be empty. The array of the last step is the result, empty or not, unless an earlier step gave several items, whose arrays are flattened into a sequence, undefined when empty. A path that starts with an array constructor is never flattened. Arithmetic, order comparisons and negation are undefined where an operand is; =, !=, in, and, or and & are always there, and so is an array constructor. A condition without else is undefined where its condition is false, ?: where its fallback is, and ?? where both sides are. A built-in’s result follows a table in typing.rs, which a test checks covers the catalog: never undefined ($exists, $count), undefined where its first arguments are (most, as in jsonata-js), or also for some values ($lookup, $filter, $keys, and $max, $min and $average of an array that may be empty). An array whose Shape::min_items is at least 1 (minItems, given by inference to an array no sample had empty, x-jlens-min-items-inferred) is never empty. A value computed from a value not fully known (an operand of arithmetic or an order comparison, the argument of a built-in) is not fully known either: it may be undefined.

A type also tells a sequence from an array. Ty::sequence is the span of the operand that may make the value several values gathered in an array: a step that runs over several items (after a step that gave arrays, but for one whose filters are all numbers, items[0]), a filter that may keep several, $filter, $keys. Ty::form tells whether the value is the shapes themselves or an array of them (an array constructor, $sort, $append, $split), or either. Paths read the items of both. A filter’s result is the items of its value, one level down (not every level, as a step’s context is). A literal index takes one item, and an index after it an item of that item (rows[0][1]); of a tuple it takes the item at its position (Shape::prefix_items, Ty::item_at), where the value is one array: not a sequence, nor the result of a step over items that are arrays themselves, which reads the values of them all. A path with a tuple stream (@$v, #$i) gives what its steps run against, which the walker does not follow: its type is unknown. A built-in’s result has the type of its signature (n, s, b).

LanguageService::result_type turns the root’s type into a ResultType: the JSON types it may have (an array for a sequence or an array form, and the values of a sequence), and the spans that make it undefined or a sequence. With an expected type declared (LanguageService::with_result_type), the diagnostics add W0212 (never one of the types, over the whole expression), W0213 (another type too: at the sequence’s operand when the other type is only the array a sequence makes, over the whole expression otherwise) and W0214 (undefined, at its cause). A text with a syntax error gets none. The suite test checks every result the typing knows against the result of the case (1,047 of 1,401 expressions are typed, 805 always defined), and a property does the same for random expressions against their sample.

While walking, the walker reports events to a visitor:

  • a field reference, with the context it is looked up in;
  • a variable reference, with its type and the scope.

The services are all visitors over the same walk.

Completion

Completion has to work on text that does not parse yet, so it proceeds in four steps:

  1. Lexical check. If the cursor is inside a string or a comment, nothing is suggested. If it is inside a backquoted name, a quoted field name is completed.
  2. The word at the cursor becomes the replacement range. If the previous token ends an operand (a name, a literal, or a closing bracket) and is not and, or or in, and there is whitespace before the cursor, operators are suggested instead.
  3. The placeholder trick. The word is replaced with a sentinel identifier (__jlens_cursor__, or $__jlens_cursor__ for variables), and the text is parsed with error recovery. The parse succeeds whenever the expression before the cursor is well formed, because the sentinel completes it. Anything broken after the cursor becomes an error node.
  4. The walk finds the sentinel’s event. For a field, it yields the context type, whose fields are the suggestions. It also yields the scope, whose variables are suggested with the declared host functions and the built-in functions.

The two field paths that matter most, items. and items[, are therefore handled by the same machinery as $map(items, function($i){ $i..

Diagnostics, hover and signature help

  • Diagnostics combine the recovering parser’s errors and annotation warnings with W0201 for every field reference whose context is fully known (Ty::is_known_objects) but lacks the field. A Levenshtein distance of at most 2 picks the “did you mean” suggestion. The walk also reports every call of a $name and every name it binds (:=, parameters, @, #); the calls are checked after the walk, because a function may call a name bound after it, or itself. Calls of unknown names get W0202, and calls whose argument count the signature rejects get W0203: parameters marked ? or - are optional, and + accepts any number.
  • The call events carry the type of each argument. Literals and operators have a JSON type (Ty::literal), schema fields have theirs, and anything else is unknown. Ty::symbols turns a fully known type into signature symbols, keeping the items of arrays apart, and the signature is matched as jsonata-js matches it (greedy, with backtracking), except that an argument whose type is unknown matches any parameter. A path may yield a single item of an array, so an array also matches what its items match. When no match exists, W0205 names the argument jsonata-js would report in T0410 or T0412. Undefined is left out: a field that is absent passes any signature, but one that is present cannot.
  • When variables are declared, the declarations are taken to be complete, and references to names that are neither declared, bound anywhere in the expression, nor functions get W0204.
  • The comparison events (=, !=, in) carry the left-hand side’s type and the right-hand side’s node, as for value completion. When every shape of that type declares an enumeration, directly or through its arrays’ items, a literal on the right outside it gets W0206; values are compared as JSONata compares them, so 2.0 is 2. Shape::enumeration_inferred marks an enumeration inferred from samples (in JSON Schema, x-jlens-enum-inferred), which never warns, and so does a type that may come from something unknown, or an enumeration that holds an array or an object. A literal with a predicate, "a"[false], is not checked. The nearest string value, by the same Levenshtein distance, is suggested for a string. A shape with an open domain (Shape::domain, x-jlens-domain) never warns either.
  • Without a declared enumeration, a literal on the right whose JSON type the left-hand side never has gets W0210, unless the left-hand side is a literal too. The operand events (<, <=, >, >= and arithmetic) carry both sides’ nodes and types. A side whose present types, an array’s replaced by its items, include none the operator takes gets W0207 (no order) or W0209 (not a number), the operand of a negation W0211, and two orderable sides with no type in common get W0208. A type that is not fully known, or holds arrays of arrays, is not checked. The suite test runs these over the official suite, which has one expected warning: a comparison guarded by $type, which the typing does not read.
  • An operand that may be several values gets W0215: its type is a sequence (Ty::sequence, the span of the step over an array, the filter that may keep several items, * over an object of more than one field, **, $keys), or its known types include an array, which a path gives whole even of one item. The comparison events also carry the right-hand side’s node and type for it: = and != warn only where the other side is one value, in only on the left. A filter of a value that holds one value (no array, no sequence) keeps it or nothing, and a number filter anywhere among a step’s filters keeps one item. An operand that is never there, with no shapes, is not warned about. A service test checks every operand built from a set of steps and filters against documents of one and two items: the warning is reported exactly where the operand evaluates to an array on one of them. The text says “is an array” where the type is known to be an array and no sequence, and “may be several values, because of” the cause otherwise. For = and !=, the hint is the expression written with in from the sides’ source (each cut to … past 40 characters), and for != with $exists of each side whose type may be undefined; another test evaluates each rewrite against documents and checks that it gives the comparison’s answer wherever the operand is not an array.
  • Value requests: where values are completed, the first shape of the left-hand side (or of its arrays’ items) with a domain becomes a ValueRequest beside the items. Its path is found by identity in the schema’s tree of shapes, iteratively; a variable’s shape has none. Its conditions come from the same probe: before the walk, an iterative search of the tree finds the comparison whose right-hand side is the placeholder and goes up through and, or and parentheses around one expression, keeping the comparisons (=, in) of each and’s other operand; the walk then types their left-hand sides, matched by address, and a field of the schema compared with literals becomes a ValueCondition. The service never fetches anything: the request is all it returns.
  • Hover keeps the innermost field or variable event whose span contains the offset, and renders its type and documentation as Markdown.
  • Signature help scans backwards from the cursor for the unmatched ( of a call, ignoring strings and comments and balancing brackets. It counts the top-level commas to find the active parameter, and looks the function up among the declared host functions, then in the built-in catalog.

Roadmap

What comes next for jlens, and what is not planned. Finished plans, one paragraph per release, are in the roadmap history, and every change in the changelog. A plan’s table lists its items, one row each: what it delivers, when it is done, and its state. The rows are in the order of the work: the items done or moved, by date, then the pending ones in the order they will run. An item keeps the number it was given, so a late item can come before a lower number.

Priorities

Three principles order the work after 0.2:

  1. The core is a library for custom integrations. Applications embed jlens-core in their own pipelines. It must stay small and decoupled, let the application set every limit, never panic, and change its API only on purpose.
  2. The CLI is a tool for automation and AI agents. It never prompts, it gives the same output for the same input, and it has one documented machine-readable contract: what goes to standard output, what goes to standard error, and what each exit code means.
  3. Editors come after. The language server is done; the VS Code extension is 0.15.

For ad-hoc JSON queries, jq remains the usual tool. jlens is for JSONata that will run somewhere else, such as a rules engine or a jsonata-js service. It checks those expressions, tests them and explains their results before they ship.

0.37: what adopters need before they evaluate

The applications adopting jlens judge it with what this plan delivers, and what they report then shapes 0.38. #4, #5 and #7 come from an outside review of the code at 7b69a6e, its claims checked before they were listed (one, a hang of $formatInteger in words, was false), and #11, #12, #19, #20 and the reader’s gaps in #9 were candidates of the same review, taken on 2026-11-27: #19 because applications will load schemas that their own users send, #20 because it slows the crate that 0.36’s UTF-16 searches were made for. #8 is the one feature of jsonata-js 2.3.0 that 0.36 left out. #9 and #10 come from applications built on jlens: their editors list a schema’s fields by walking it by hand, and corporate pages set a Content-Security-Policy that the guide does not mention. #13 follows from #9: when a schema’s new version renames or moves fields, the expressions stored against the old one are rewritten from a table of paths that the application builds from the two lists. #14 measures what the WebAssembly module, grown by a quarter since 0.27, is made of, for 0.38’s ADR. #21 comes from a second outside review, of the code at 285e0b7: #13’s rewrite could change what an expression means, so it is fixed before the release; that review’s other findings open 0.38. #3, from 0.36 #8’s review, lets the release workflow follow the channels’ tiers. #1, #2 and #6 are now 0.38’s. #15 opens the plan and #16 to #18 close it, as in every release. Between them the rows run from the fixes to the features, and #3 comes just before the release that first uses it. As in 0.36, an item names in its status the choices it made that the maintainer has not reviewed.

#ItemDone whenStatus
15The dependencies at their newest versions and the upstream watch, before the restThe dependencies of step 1 of the release checklist, Dependabot’s pull requests merged and the pins it does not see (such as TypeScript for the check of types.d.ts, and ovsx); stacker (#155, #156), regress after 371ab39 and jsonata-js (npm after 2.3.0, main after 361156d, pull request #875, whose monthNameCase.json is vendored once it merges) checked; what they bring becomes an item of this plan or is recorded with the reason it waitsdone on 2026-11-27: nothing to update. Cargo (also in fuzz/) and every direct dependency were at their newest releases, as were npm (no advisories), TypeScript, ovsx, binaryen, Maven, its plugins and Wrapper, JUnit, the actions’ majors and maturin. One exception: vscode-languageclient 12.0.0, a major published that day with no release notes yet, waits out Dependabot’s three-day cooldown and goes to step 1 of the release checklist at #16. The upstreams had not moved: stacker (#155, #156 open), regress (still 371ab39, crates.io 0.12.0), jsonata-js (main 361156d, npm 2.3.0, #875 open at fcb4471 with no review)
4The C API and the Java package under threads and failuresEach reproduced by a test before it is fixed: a document freed while an idle pool thread still caches its text (documents.rs’s FOUND), so that no thread sweeps its conversions; Bindings.close during an evaluation, whose host function then throws IllegalStateException; critical(false) on BUFFER_* downcalls that lock and free; BUFFER_FREE outside a try/finally; Json.java and Read.java, recursive, over a value 1,000 levels deep at -Xss128k; Options.NATIVE, which never evicts, so that after 64 distinct options (a now per call) every other one makes and frees its native object per evaluationdone on 2026-11-27, each reproduced by a test that failed first: a thread’s conversions are kept by the document’s handle and swept when the table’s count of removals moves, so no thread holds a document’s text between its calls; an evaluation’s Host keeps its bindings’ functions from its start; no downcall is critical any more (a System.gc() waited 163 ms for a sweep of 170 ms inside one); replies and new buffers are freed in a finally; Json and Read use stacks of their own; Options keeps 64 native objects with a second chance, each freed by the Cleaner once no evaluation holds it. Choices not reviewed by the maintainer: Read.Fields compares, hashes and prints by its JSON form (toString is now Fields[{...}]); the three buffer calls lost critical, not only the one that frees, as each sweeps and locks: measured on the M1 with java-compare ab, no case slower past the mark, JSON text within ±0.8%, path on a Document 5.6% faster (finding the conversion by handle), host-function calls not timed (docs/notes/perf-0.37.md); the garbage-collection test is timed, skipped when the sweep takes under 80 ms; options let go are freed by the garbage collector, not at once
5No allocation past the size limits$replace checks max_string_length while it builds its result; the review’s other cases (filter_items, $split, $pad, $join on wasm32, $fromMillis) checked, and fixed where they allocate past a limitdone on 2026-11-27: each allocated past its limit, measured by an allocation probe (20-390 MB built against limits of 100,000 bytes or 1,000 to 10,000 items) and now stops at it: $replace in its three loops and inside $0 and groups, $split and $match (also past the review’s list) counted as they push, $pad before it builds, $join’s sum without overflow, $fromMillis as each marker is written; a filter whose predicate repeats a position was not limited at all (a test that failed first). ab on the M1: a check per piece made $replace 7-13% slower, one per match with the error out of line brings it within 1.3% (docs/notes/perf-0.37.md). Such a filter now fails with U1001 where it gave a result past max_array_length: approved by the maintainer on 2026-11-27
12No Python code inside a critical sectionFree-threaded Python: source.rs writes a list’s item while it holds the list’s critical section, and writing it may call the item’s own methods (a Mapping’s, a subclass’s), which may suspend that section; reproduced by a test on free-threaded CPython before it is fixed, or shown not to happen and the reason written beside the codedone on 2026-11-27: it happened, reproduced by a test that failed on CPython 3.15 and 3.15t: an int subclass beyond 64 bits was read by its own __float__ (PyFloat_AsDouble), a str subclass with a lone surrogate by its own encode, and code there that changed the container made the read fail with U1004, or panic in a dictionary (PyO3’s iterator); both now call the built-in type’s function (int.__float__, str.encode with "utf-16", which also skips the codec registry’s search function, written in Python). The other reads were checked and the reasons written in source.rs: types told apart by their flags, collections only between bytecodes since 3.12; left, on GIL builds only, a metaclass’s __name__ in an error message on 3.10 and a collection at an allocation on 3.10 and 3.11. Only rare values take a new path, so not measured. Choice not reviewed by the maintainer: such an int subclass gives the float of its value, not what its __float__ returns, as json.dumps writes its value
11The workflows hardenedEvery action of .github/workflows pinned by commit SHA, its version in a comment, kept up to date by Dependabot’s github-actions updates; concurrency on the workflows that a newer push makes stale (not on release.yml); an unknown xtask subcommand fails with its usage instead of exiting 0; actionlint cleandone on 2026-11-27: every external action of the eleven workflows pinned at the commit of their newest tag in their major (pypa/gh-action-pypi-publish at v1.14.3, not its branch release/v1), and actionlint’s download script at the commit of v1.7.12; dtolnay/rust-toolchain, which has no tags, at a commit of master with toolchain: as its input, and no longer ignored by Dependabot; concurrency only on ci.yml, whose runs on a pull request cancel the one before them (pages.yml had its own, and the other workflows run on a schedule, a tag, a release or by hand); cargo xtask with an unknown command or none exits 1, help prints the usage. Choices not reviewed by the maintainer: runs on main are never cancelled, each commit in a group of its own, since release.yml needs the run of the tagged commit and one shared group would cancel a waiting run; whether Dependabot moves a pin with no tag (dtolnay/rust-toolchain) is seen at its first weekly run, and step 1 of the release checklist now names it otherwise
10Serving the module: a Content-Security-Policy and its size in the WebAssembly guideThe guide says which directive a page needs to compile the module ('wasm-unsafe-eval' in script-src), what fails without it and how the error reads, tried in a browser with the header set; and how to serve it small: the .wasm with brotli (about 470 KiB at 0.36.0, against 637 KiB with gzip), jlens.js with the .wasm beside it, compiled while it downloads, rather than jlens.global.js, whose module in base64 compresses worse and is compiled only once it has all arriveddone on 2026-11-27: the guide’s “Serving the module” says it, each policy tried with its header in Edge 158 and Firefox 160 against jlens.js and jlens.global.js: without 'wasm-unsafe-eval' both reject with a CompileError, whose text in each browser the guide quotes; a connect-src that leaves out the module’s origin makes jlens.js fail to fetch it, and jlens.global.js fetches nothing. Measured on today’s build: the .wasm 640 KiB with gzip, 471 KiB with brotli at quality 11 and 540 KiB at 5 (a server’s usual level on the fly), jlens.global.js 920 and 652 KiB; also Content-Type: application/wasm, without which the module is compiled only once it has arrived. The guide’s sizes of 0.27 (535 KiB, 745 KiB, 3.4 MB unpacked) corrected. No code changed. Choice not reviewed by the maintainer: the guide gives the sizes as 0.37’s, from a build before the release, which #16 refreshes
8Template strings, as jsonata-js 2.3.0 reads them (pull request #860)«...{expr}...» parsed and evaluated as in 2.3.0, with its escapes and nesting, and its errors’ codes; "a" & «x» is “ax”; the 69 cases that use them (68 of the group template-strings and function-eval/case009) in the baseline (1,970 of 1,972, the other two the overrides of a lone surrogate); the lexer, the parser’s limits and the property tests, the language server and the VS Code grammar (which tokenizes the suite), the book’s syntax pages and compatibility.md’s row removed; “JSONata 2.2” in the READMEs and the introduction becomes 2.3done on 2026-11-27: the lexer reads them as jsonata-js does, with a stack of open templates that counts the braces of each expression, and the parser builds a NodeKind::Template of text and expressions, each part’s value cast as & casts it and the size limit checked as each is added; 1,970 of 1,972 in the baseline, template-strings/case048 ({1/0}) through an override, as jlens fails with D1001 at the division where jsonata-js’s cast fails with D3001 (the row of an overflow to infinity in compatibility.md). Recovery keeps the parts read, with jsonata-js’s codes and positions; templates nested 5,000 deep fail with U1001; the property tests (20,000 cases) and the differential generator make them, 5,000 cases with no difference. The language service completes, hovers and checks inside their expressions and nothing in their text, and signature help counts their braces; the VS Code grammar scopes them (string.template, meta.template.expression) and pairs «»; the book’s operators page has a section, and the 2.2s became 2.3. Not measured: the lexer checks for a template at each token and the evaluator has one more kind of node, which #16’s ab and #17 cover. Choices not reviewed by the maintainer: string literals take 2.3.0’s escapes too, so a \ at the end is S0103 (it was S0101) and \u with fewer than four digits there S0104; NodeKind gains a variant, which breaks an exhaustive match outside the crate; the status lines of the README and the introduction, which name 0.36, are left to #18
7A regular expression literal compiled once per expressionKept in Compiled by node, with no key cloned each time the node is evaluated; the two fixed patterns of datetime.rs (parse_iso8601, words_to_number) compiled once, not per call; ab on the M1done on 2026-11-27: each compiled pattern is kept in Compiled, by node, filled by the first evaluation that meets it on any thread and found by the node’s address, so that a tree $eval parsed never takes another’s; each evaluation keeps its own by node id, with no key copied; an invalid pattern is not kept. The two patterns of datetime.rs are statics. ab on the M1, evaluate and document modes: regex 15-16% faster, $toMillis without a picture 92% and $parseInteger in words 35% (cases added for the run), every other case within ±1.7%. The first version, its code out of eval_inner, made group-by and shipping rule 9-10% slower, aligned builds too: eval_inner’s frame changed, so the code is inlined there (docs/notes/perf-0.37.md). No choice for the maintainer to review: behaviour and errors unchanged
20jlens-regress’s utf16 feature without a slower search of &strThe feature turns off the prefix search of &str searches (upstream 542243a, skipped), so a crate that enables it for 0.36’s interruptible UTF-16 searches makes every other search slower: measured, then the prefix search kept for &str with the feature on, or 542243a ported; cargo test -p jlens-regress --features utf16; released as jlens-regress’s own versiondone on 2026-11-27: measured on the M1, &str searches with the feature were up to 128 times slower (literal, no match), as they tried every position. 542243a, 3e43472 (the interrupt in place of the budget), c57833c and 851f87b ported, each in a commit of its own; they gave &[u16] a start predicate in code units (48-90% faster with a literal or a small class first) and &str its predicate back, but the feature keeps literals as chars, which the byte predicate skipped (literal still 12 times slower): a char now gives its UTF-8 bytes there, a run taken whole, a change of the fork’s own. With the feature, &str searches are within 8% of the build without it, but literal +30% (its program matches char by char); without it, every case within ±1.2%. The benchmark also searches UTF-16 (JLENS_REGRESS_UTF16). jlens-regress 0.35.2 (docs/notes/perf-0.37.md). Choices not reviewed by the maintainer: the char predicate, which upstream lacks, only under the feature, so that the default build stays upstream’s; UTF-16 searches whose predicate is \w or \S 3.5-5.5% slower, upstream’s scan kept as written
9The fields of a schema, listedThe language service lists a schema’s fields: each path with its type, whether it is required, its label and description, its allowed values and its open domain, as completion and hover know them, and the field’s own x- keywords as written, which jlens does not read (such as an application’s stable key for the field), overrides applied and hidden fields left out, so that an application builds its list of attributes, or matches the fields of two versions of a schema, without walking it; in Rust, Wasm and Java, with an example in each guide; first, the gaps of the JSON Schema reader that the list would show, each with a test: allOf’s required, required without properties, closed tuplesdone on 2026-11-27: the reader’s gaps first (commit 7626b55): a field that one branch of allOf required was optional where another listed it, properties beside a $ref replaced what it said of a field, and a required with no properties beside it was not read; now a branch of allOf or a $ref’s target hands up what it requires without listing it, a field required and listed nowhere is a field of unknown shape (it got W0201), and in anyOf a field is required where every branch requires it. A tuple closed by false was written back with its items as the rest, which opens it: Shape::max_items keeps the bound, read from maxItems too, and the export writes "items": false. Then Schema::fields and LanguageService::fields (ListedField), jlens_service_fields in the C API and service.fields() in Java and WebAssembly: each path with its type summary as completion shows it, its types, required, label, description, values and closed, domain, format and extensions, a JSON Schema’s x- keywords that jlens does not read, now kept on Shape::extensions and written back (those of a $ref‘s place before its target’s); hidden fields left out with what is under them; fixtures/fields/cases.json pins the JSON for every package; a property checks the list against what uses gives for a whole read, under random overrides. Not measured: no evaluation code changed; uses now shares its walk with the list (walk in uses.rs), which keeps the shapes written at each place too. Choices not reviewed by the maintainer: the list is of the input’s schema only, not of the variables’; in the order of the paths, as uses, not the schema’s own order; with $ and the items (lines[]) as entries, and no entry per position of a tuple; no CLI command and nothing in Python, which has no schema service; an enum with no type stayed of unknown type outside anyOf (changed before #16 at the maintainer’s request: such an enum or const now has the types of its values everywhere); maxItems is read everywhere but the typing does not use it (an index past a closed tuple is still typed as every item); unknown x-jlens-* keywords are kept as extensions; overrides cannot set extensions; a field required by a schema that gives no type is not added, as nothing is known of that value
13Paths renamed in an expressionGiven a table of paths, old to new, the language service rewrites an expression: only the steps that read a renamed path change, found as uses finds them (relative paths in a predicate, a parent kept in a variable, the same name under another parent left alone), the rest of the text kept as written, a new name that needs them in backquotes; the answer gives the rewritten text, each edit with its range, and the places it cannot rewrite safely, where a field is named as data ($lookup with a string, *, **, $keys, $sift); in Rust, Wasm and Java, tests over the cases above and property tests; the schema guide shows a schema’s new version migrated: changes, the table (built from the two versions’ fields(), matched by a key of the application’s in extensions, as #9 lists them), the rewrite and the check with usesdone on 2026-11-27: the analysis of the reads, when asked (Expression::sites_with, reads::Sites), keeps each name that reads a field with the places it may read, and each value used whole with the operand that uses it; an object the expression builds gets a place of its own there only, so that a step over it and a renamed field is not renamed. LanguageService::rename, jlens_service_rename in the C API and service.rename(...) in Java and WebAssembly check the table (a path it cannot read, a field moved to another parent, renamed twice, two renamed to one path, a name with a backquote fail) and replace each step whose every place is renamed alike; unsure lists the rest with its reason: whole (a value holding a renamed field used whole: $keys, $sift, *, **, a lambda’s or an undeclared host function’s argument, the input of a transform), string ($lookup with a string), mixed, lost ($eval, too many places). fixtures/rename/cases.json pins the JSON, spans in UTF-16, for every package; the property tests check that an empty table gives the text back, that the rewritten text parses, and that with nothing unsure it gives on the input with its keys renamed what the expression gave (both its checks failed under mutation); the schema, Java and WebAssembly guides migrate a rule to a new version: changes, the table from the two versions’ fields(), the rename and the check with uses. Not measured: no evaluation code changed; the analysis notes its node as it goes, two stores a node, and an expression against a Document runs it once when compiled. Choices not reviewed by the maintainer: the input’s fields only, not the variables’; any value above a renamed field used whole is listed, $count(lines) and $exists(customer) too, which read no name; $lookup with a string is listed, not rewritten, as the definition says; the result of the expression is not listed, though an object it returns holds the new name; a table entry that keeps its name may be left out or given; a bad table fails with a message (String in Rust, U2005 with the token renames in the C API and Java, TypeError in WebAssembly, which takes the text, not an Expression, as uses takes reads); nothing in the CLI or Python
19Fuzzing what applications send to the language serviceTargets in fuzz/ for loading a JSON Schema, for parse_cut and for #13’s rewrite, seeded by cargo xtask fuzz-seed and run by the weekly workflow; the rewrite’s properties also in the property tests: an empty table gives the text back, and a rewritten expression parses; what they find fixed, each with a testdone on 2026-11-27: three targets, each checking what must hold of its answer, not only that it does not panic. json_schema reads a JSON document as a JSON Schema (which also refers to itself under another URI) and as a sample: what is written back reads again, and as itself the second time; the listed fields read back from their JSON form, and the service knows each listed path. parse_cut checks that a document cut by what an expression reads is the value cut, and gives the expression’s result or error code as the whole one does. rename checks that an empty table gives the text back, that the edits make the text and that it parses, and, renaming every field the expression reads, that with nothing unsure the result on the input with its keys renamed is the same. Seeded from the suite and the schemas and tables of fixtures/, in the weekly workflow; run 10 minutes each in WSL with no failure (313,462, 218,393 and 217,130 runs). Found and fixed, before the first run: a name that begins with «, written without backquotes by completion, rename, uses and fields, opened a template string since #8 (a test in rename.rs). The two properties of the definition were already in the property tests (#13). Choices not reviewed by the maintainer: a name that holds a backquote, which JSONata cannot write, is still listed by fields with a path that does not read back, as uses documents, and the target does not check its path; in rename’s comparison, a field called as a function fails with T1005 or T1007 where its name is a built-in’s, before its arguments are evaluated, and once renamed with T1006 or T1008 or with an error of its arguments, so the target asks only that it fail (it took the codes as the same until #16’s two runs of the workflow found min(it%ms{k:v}.[H]) and count([/a/- /b/]), whose arguments fail with T2002 and T2001 once renamed); it does not compare a result that holds an object, which keeps the new names, as the property test does not
14What the WebAssembly module is made ofThe gzipped .wasm grew from 518 KiB at 0.27 to 640 KiB at 0.36, its budget raised twice, mostly with the language service: measured by crate and by part (twiggy, or a build without the language service), so that 0.38’s ADR 0015 decides with the numbers whether a page that only evaluates gets a module without it; the gzipped size of each release written in its performance notes, and a raise of the budget given its reason theredone on 2026-11-27, in docs/notes/perf-0.37.md: each release’s module since 0.20 from its npm package, and 0.37’s commits built one by one; the two large steps were 0.33’s schemas (+47.9 KiB) and 0.34’s types (+33.4 KiB), and 0.37 adds 35.7 KiB, half of it rename (+17.8 KiB once the module exports it), so that HEAD is 673 KiB, about 6.5 KiB under the budget. Built without the language service, the module is 505 KiB gzipped (374 KiB with brotli), a quarter less; with evaluation alone, 476 KiB. By crate, jlens-schema and what it brings are that quarter; regress with its Unicode tables (about 38.5 KiB gzipped) and jlens-core the rest. The release checklist now writes the size and any raise’s reason in the plan’s notes, and the budget’s comment points there. No code changed. Choices not reviewed by the maintainer: no second module and no Cargo feature, left to 0.38’s ADR 0015; rename‘s size left as it is (its two stable sorts are about 6.8 KB of code before wasm-opt); the notes’ sizes from Python’s zlib, up to 1.5 KiB under what cargo xtask wasm prints
3The release workflow’s tiersThe github job of release.yml waits only for the tier-1 channels of 0.36 #8 and the binaries it attaches, so that a failed container or vscode job no longer holds the draft, and with it Homebrew and Scoop; tried on a tag of a fork or a dry run before the release that first uses itdone on 2026-11-27: the job waits for crates, npm, pypi, maven and binaries; tried in a scratch repository on a stub of the workflow (the same jobs, needs and if, each step passing or failing), beside the 0.36 graph as a control: with npm-cli, container and vscode failing the draft runs (0.36: skipped), with crates failing it is skipped in both, and run by hand it drafts in both. Not reviewed: the draft may now come before the tier-2 jobs end, so release step 6 waits for the whole run before publishing it
21Paths renamed without changing what the expression means0.37 #13’s rewrite, as the review of 285e0b7 found it, each case a test that fails first: a name taken out of its backquotes is kept in them where the next character continues a name (`a`and b gave xand b, which does not parse, and `a`or(b) gave xor(b), a call, with nothing unsure); a step written as a string (customer."name") renamed, not Lost; a path that may be an object the expression built (group-by, $clone, $sift, $spread, $match, a transform, a function’s result) unsure as Mixed; parse_path and Table::new reject a backquote left unmatched and leading dots; hover and W0201 give the name’s range as written, backquotes and quotes included, never inside a character (`café` gave 0..5), with a property that every range falls on character boundaries; the rename’s fuzz target keeps its table whole past 64 fields, or stops before it is cut; the gzipped .wasm within its budget (6 KiB left at 285e0b7)done on 2026-11-28, each case a test that failed first: a name keeps its backquotes where the text beside it is a name’s character; sites_with takes a step written as a string from its start to its token’s end; the result of a group-by, of a function of the expression’s or the application’s, of a built-in whose signature may give an object ($sift, $spread, $match, $lookup…), of * and **, a lambda’s parameters and $reduce’s accumulator are objects the analysis does not follow (built), only when sites are recorded, so reads and the cut do not change; parse_path rejects a stray backquote and an empty name, which shape_at and the overrides follow; hover and W0201 take the name’s token, with a property on character boundaries; the fuzz target gives up past 64 fields. The rename property, given a group-by beside a renamed parent, finds the old analysis’s rewrite; 20,000 cases of the schema’s properties and both fuzz corpora pass. The gzipped .wasm: 690,047 bytes, 6.1 KiB under its budget
16The plan’s code checked whole, and the release’s measureOn the Ryzen, which need not be idle: the robustness properties with PROPTEST_CASES=100000 and cargo xtask differential with 20,000 cases, on the final code; the sizes of the JAR and of the gzipped .wasm against 0.36.0’s, written as #14 says, and the WebAssembly guide’s table of sizes (#10) from the release’s build. The fuzz workflow on the final code once the maintainer has pushed it (or its targets run in WSL until then). On the M1: the performance page’s tables, and cargo xtask ab against 0.36.0, with jsonata-js 2.3.0 as the control (the other engines only where their version changed)done on 2026-11-28: the differential with 20,000 cases and the regex one, none differing (at 4e93221; the evaluation has not changed since); the robustness properties with PROPTEST_CASES=100000, at 285e0b7 and, for jlens-schema and jlens-lsp, again after #21; on the M1, cargo xtask ab, python.py ab and cargo xtask java-compare ab against 0.36.0 and the performance page’s tables (d050038), with jsonata-js 2.3.0, jsonata-python and jsonata-java as the controls, each within 4.6% of its 0.36.0 column: regex 7 to 18% faster on every platform (#7), $toMillis of an ISO text 88%, and WebAssembly’s regex over a long text 4% slower, in two steps of about 2% (#5, #20), left; the sizes on the final code: the gzipped .wasm 673.9 KiB (+5.7%), the JAR 11,865,124 bytes (+5.4%), and the guide’s table of sizes; the fuzz workflow, 600 s per target, at 3de4de0, every target passing. vscode-languageclient 12.0.0 waits out Dependabot’s cooldown (until 2026-11-30) and goes to step 1 of #18’s checklist
17The release’s x86_64 check, on the RyzenWhen the plan changed the evaluation (#7, #8, #12) without measuring every such change on x86_64: cargo xtask ab v0.36.0 HEAD natively under Windows and python.py ab under WSL, into docs/notes/perf-0.37.md; otherwise left out, and the reason written theredone on 2026-11-28 at 91abf60, as #5, #7 and #8 were measured on the M1 alone: natively regex 10 to 12% faster in every mode; filter + aggregate against a Document +11%, level when built aligned (layout); the shipping rule +2 to +5%, aligned too, with no step past the floor along the plan’s commits and on the M1 within 2.9%. In Python regex 12 to 14% faster and nothing slower past +2.7%. Nothing for the page or before the release
18Release 0.37.0The release checklist, the first with #3’s tiers; the channels checked; the status lines of the README and of the book’s introduction with the suite after #8; the plan leaves the roadmap for a paragraph of the roadmap historyprepared on 2026-11-28, not yet tagged: the dependencies current (cargo update moved nothing, here and in fuzz/; npm audit clean in editors/vscode and benches/compare; no Dependabot proposal or alert open), except vscode-languageclient 12.0.0, a major published on 2026-11-27 that waits out Dependabot’s cooldown (until 2026-11-30) for 0.38’s first item; upstream as #15 left it (stacker two commits for other platforms, #155 and #156 open; regress 371ab39; jsonata-js main 361156d, npm 2.3.0, #875 open at fcb4471); the version in the snippets, the issue template and the extension, the suite’s 1,970 of 1,972 in the README and the introduction, the changelog’s section and the history’s paragraph; before the tag, cargo package, wasm-test --require-browser --example, npm pack --dry-run, fmt, clippy with warnings as errors, the workspace tests, gen-docs --check, doc-check, the book’s examples against jsonata-js (251, none differing), cargo doc, cargo xtask java and cargo deny; Maven Central holds 11 releases of November, of the 24 allowed

Candidates from the same review, not planned: the type checker (~> with a transform, a host function’s declared result), the language server (code actions, its cache dropped on any .json change), the CLI (--var, - for stdin, --ndjson flushed per line), and the Python package (a seed of 2^64 reported as negative, counts read as usize, Self from typing_extensions in the stub).

0.38: what the Java adoption shows

The applications in Java adopting jlens evaluate it with 0.37’s features first. What they report then decides how a result is kept for later rules and which gaps the API’s inventory lists. #1 and #2 came from 0.36 through 0.37, and #3 from 0.37’s outside review. #4 to #13 come from the outside review of the code at 285e0b7, its claims checked before they were listed: one was false (a value parse_cut skips is read without recursion by serde_json), and a few are left out below. The fixes come first, as they need no report. The rest of the plan, its habitual items among them, is drafted when it starts.

#ItemDone whenStatus
4Signatures and arrays within the limitsA signature is matched in polynomial time, with no recursion per parameter (twenty n+ and forty arguments meant 7·10^10 calls, and a million n? overflowed the stack); a group-by’s items and * count against max_array_length (both gave results past it); ^ keeps the keys of each term as it reaches them, not items × terms slots up front; a..b checks the limit before it builds the range, and fails past 2^53, where it gave wrong numbers ([1e20..1e20] gave [9223372036854776000]; jsonata-js fails), the difference in compatibility.md; each case a test that fails first, ab on the M1 for the signatureplanned
5Shared values walked within the limitsA value made of the same arrays many times over ($a := [$a, $a], forty times in a short expression) is walked by $boolean, $keys, $lookup, $spread, *, = and $distinct and ** within timeout, max_steps and the cancel token (depth 22 ran 430 ms against a 5 ms timeout, each level doubling it); = compares a pair of shared nodes once; ab on the M1, as these walks are on common pathsplanned
6A predicate or group on a block binds in the block($x := 1; ((1)[$x := 2]); $x) gives 1 as in jsonata-js, not 2, and so the group ({...}) and the predicate of a lambda: mark_frame reads the stages and the group of a block or lambda; the cases in the differential tests’ generator; mark_frame’s comment moved back to itplanned
7The C API and the Java package, second passEach reproduced by a test before it is fixed, or shown not to happen: a List whose size() throws makes $count give a buffer’s handle (Reader.read answers a failed LENGTH with -1); a host function’s exception kept for later after the outermost call cleared FAILURES, or before its call began; FOUND_BINDINGS, FOUND_EXPRESSIONS and FOUND_OPTIONS swept as #4 of 0.37 sweeps DOCUMENTS; Options’ eviction with a hand that persists; Reads.fromJson strict as JSON (spaces, trailing text, unknown fields, escapes and numbers); AuditNode’s equals and hashCode without recursionplanned
8The Python and WebAssembly packages, second passEach reproduced by a test before it is fixed: register_function and __clear__ drop the functions they replace after the lock (a __del__ that evaluates deadlocked); the limits read inside the dict’s critical section; a getter or Proxy that throws while bindings, a function’s length or an error’s message are read leaves no host frame behind (imports with catch); the fallback to JSON.stringify for more than 16 items calls no toJSON a second timeplanned
9Checks, the CLI and the docsCI runs jlens-regress’s unit and doc tests with utf16, not only tests and interrupt; the npm job of release.yml checks the tag against the workspace’s version, as the other publishing jobs do; the fuzz corpus keyed by run attempt too; xtask wasm honours CARGO_TARGET_DIR; eval --now -1000 accepted; schema reads a file named with [ as itself; word_values built once; explain_node and Shape::observe through stack::grow; conformance.md’s overrides and count of kinds, cli.md’s synopsis, CONTRIBUTING.md’s last check, value.rs’s 128 levels and jlens-capi’s U2005 tokens (renames) brought up to dateplanned
10jlens-regress with no unsafe path, and its UTF-16 literal searchuppercase’s cfg! turned the right way (the fork’s own change, reported upstream); positions by index (index-positions) measured with ab and turned on, or ADR 0009’s claim that no unsafe path runs corrected; a literal searched in UTF-16 in linear time, or within the interrupt; cargo test -p jlens-regress --features utf16; released as jlens-regress’s own versionplanned
11The JSON Schema reader, second passEach a test that fails first: the items of a closed tuple read as either position (either, not merge: a false W0206 and W0209); a $ref with % in it read back as itself; required and properties beside a $ref kept; allOf merges minItems, hidden, the bounds and the examples, and items inherited; x-jlens-hidden on a definition honoured; nothing indexed inside x- keywordsplanned
12The language server and the VS Code extension, second passA completion inside backquotes shown by VS Code (filter_text); "schema": "../x.json" in jlens.json followed; completion and signature help in templates («, », \{, regular expression literals); field paths written by field_insert; the grammar reads .<<...>> and . before a regular expression; autoCloseBefore, wordPattern and the quotes inside «{...}»planned
1An evaluation’s result kept as a DocumentIn the core, the C API and Java: a result used as the input or a variable of later evaluations with no conversion, such as an index of a record’s items by key built once for many rules; measured against the index built by each ruleplanned; waits for the adoption’s reports
2ADR 0015 proposed: what 1.0 will promiseItem #1 of the deferred plan below, with no change to the API: the inventory of public items and contracts, each stable, hidden or #[non_exhaustive], and the gaps adopters logged (host function context, offset conversion, a diagnostic’s details as data, a quick fix as data, such as W0215’s rewrite, the fields of an AST node that a visual builder reads, typed in types.d.ts or said to be hidden); the errors of jlens-schema, a String today (JsonSchema::load, Uses::from_json, 0.37 #13’s rename), or a type of their own; whether a page that only evaluates gets a WebAssembly module without the language service, from 0.37 #14’s measure; the ADR left proposed for the maintainerplanned; waits for the adoption’s reports
3Unknown evaluation options in Wasm{ timeot: 100 } fails as in Rust, Python and Java, or the difference documented; decided with #2, as failing may break a callerplanned; with #2
13evaluate(null) in Wasmnull as the input is JSON’s null, as in jsonata-js, evaluateJson("null") and new Document(null), not “no input” as wasm-bindgen reads an Option (the JS suite itself passes null for no input), or the difference documented; decided with #2, as the change may break a callerplanned; with #2

Candidates from the same review, not planned: a frame kept by cyclic without a closure (unmeasured), audit::describe and snippet (cosmetic), unionReads given arrays (serde reads a struct from one), jar.yml‘s set -eu (a failed apk add fails the step anyway), and the release builds’ container images by floating tag and rustup by curl | sh.

In exploration: a regular expression engine of jlens’s own

jlens-regress is a backtracker. A catastrophic pattern runs within the evaluation’s limits (ADR 0009), but it still runs to them. Its positions are code points, which jlens converts to UTF-16. On the engine’s benchmark, V8 is 2 to 11 times faster.

An engine of jlens’s own could find a match in linear time wherever the pattern allows it: an automaton finds the match, and the backtracker is left only to extract its groups, or to run the patterns that need it (backreferences, lookarounds). It would also have the interrupt and UTF-16 positions built in, with no unsafe.

This is research, not a release. The work lives apart from jlens-core, and the corpus, the differential test and the benchmark of 0.22 measure it. It ends in a decision: an ADR that adopts the engine in place of jlens-regress, or drops it. Adopted, the swap becomes a release of its own.

#StageDone whenStatus
1The linear-time path on the patterns it can take, with the interrupt and UTF-16 positionsIts share of the corpus’s patterns and their answers, against V8’s
2Every pattern: the backtracker for the restThe corpus (19,108 cases) and cargo xtask regex-differential with 20,000 cases clean, or each difference recorded with its reason
3Speed and limits, against jlens-regress and V8The engine’s benchmark and interrupt_cost; catastrophic patterns timed
4The decisionAn ADR: the engine replaces jlens-regress, or is dropped, with the measurements

Deferred: an API to keep, toward 1.0

After twenty releases, nothing says which parts of jlens are meant to last. cargo semver-checks runs in CI, but before 1.0 it only asks for a new minor version, and jlens-core exposes workspace plumbing (stack, debug, the AST’s internals) next to its API. This work decides what 1.0 will promise, breaks the API once to get there, and writes the promise down. It takes the number of the next release when it starts. Applications built on jlens are separate projects: they use jlens-core as any application does, and what they lack comes back here as general features.

Deferred until applications built on jlens have used it: what to keep stable is decided from what they needed, missed or worked around, not guessed beforehand. They have now, and #1 starts as 0.38 #2; the rest waits for the ADR.

#DeliverableDefinition of doneStatus
1ADR 0015, what 1.0 promises: what is stable, hidden or #[non_exhaustive], belowThe ADR accepted, with the list of changes that #2 to #4 makeproposed in 0.38 #2
2jlens-core changes as ADR 0015 says, in one breaking batchcargo semver-checks reports only the intended breaks; the changelog has a migration section; the crate guide’s snippets updated
3jlens-schema and jlens-lsp changes as ADR 0015 saysAs #2
4The contracts outside Rust, as ADR 0015 says: the Wasm API, the Python package, the Java package, the JSON of audits and jlens.json; a test pins each, so that a change shows in reviewTests that fail on an unintended change of each contract
5A stability page in the book, from ADR 0015, and the rules for changing a stable item in CONTRIBUTING.mddoc-check green; the page linked from the introduction
6A source that fails with a JSONata code, below; a change to public traits, so it goes with #2’s batchThe same input nested too deep fails with the same code from every input and package; a cycle stays U1004
7The release that breaks once. 1.0.0 follows when ADR 0015’s criterion is metThe release checklist, with the migration notes in the release notes

#1, what ADR 0015 decides. Exploration: list the public items of jlens-core, jlens-schema and jlens-lsp (rustdoc JSON or cargo public-api) and the contracts outside Rust: the Wasm API (types.d.ts), the Python package, the CLI (ADR 0008), the JSON of audits and explanations, jlens.json, the error codes. For each item: stable, hidden (#[doc(hidden)], pub(crate)) or #[non_exhaustive] where it may grow. What semver covers and what it does not (messages, Display, Debug, performance, jsonata-js quirks), the MSRV policy, deprecations.

#6, a source that fails with a JSONata code. Found by 0.26 #9: Source and Sources fail with a message, which the core always turns into U1004, so input nested more than 1,000 levels deep fails with U1001 as JSON text and with U1004 as Java objects or a C API host’s values, read as the expression goes; the C API also gives one message for a cycle and for deep input, as it cannot tell them apart. The error type of the reading methods carries a code (U1004 by default, U1001 for nesting), and each source says which limit it met; in the C API, a node inside itself that the host does not report (the Java Reader does) is seen as deep input. The WebAssembly package has the same gap for its exceptions: it keeps the first one a level throws, which since 0.27 #6, where a level may be read in case it is needed (ADR 0010), may not be the level that stopped the evaluation. A change to public traits, so it goes with #2’s batch. Done when: the same input nested too deep fails with the same code from JSON text, a Document, Python, JavaScript and Java values and a C API host; a cycle that the host or package detects stays U1004; the exception rethrown in WebAssembly is that of the level that failed; tests in each package.

Not planned

  • Asynchronous functions. A host function that returns a promise fails with U1002, and jlens does not plan to change that. Supporting it needs an evaluator that can suspend, which would slow down every evaluation, and only WebAssembly would gain from it: a Rust host function can block. An application can fetch what its functions need before evaluating. Should real use call for it, the cheaper way is an evaluateAsync that stops at the first promise, awaits the pending ones and evaluates again with their results.
  • Validating documents against a schema. jlens-schema reads a JSON Schema to help people write expressions: completion, hover and diagnostics of the expression. It does not check that a document follows the schema, which JSON Schema validators do. The diagnostics hold for documents that follow their schema; an application that cannot trust its documents validates them first, or checks the type of each result.
  • Compiling an expression to its host’s code. jsonata-jvm-compiler and jsonata2js translate an expression to Java or JavaScript and let the host’s JIT compile it, which makes them faster where an expression does much work per item. Rust has no compiler at run time: compiling when the application is built would serve only expressions known then, and generating WebAssembly would help that package alone, where a Content-Security-Policy allows it. jlens lowers what each node costs in the core instead (0.32), which every package gains from.

Roadmap history

What each plan of the roadmap set out to do and what it shipped, one paragraph per release. The changelog lists every change. Item numbers cited elsewhere, such as “0.27 #6” in an ADR or a performance note, are rows of the plan’s table: the roadmap at the release’s tag holds it (git show v0.27.0:docs/src/architecture/roadmap.md), and each item’s commits name it (git log --grep "Roadmap 0.27 #6").

How 0.1 was built

jlens was built in phases. A phase was complete only when its documentation was written.

#DeliverableDefinition of done
0Workspace, CI, documentation skeleton, conformance harnessCI green; conformance report
1Lexer, Pratt parser, AST post-processing, spans, recover mode, annotations; jlens ast / jlens checkSyntax groups of the suite and the parser-recovery cases pass
2Value model and evaluator (paths, sequences, predicates, operators, lambdas, closures, tail calls, sort, group-by, parent operator, transform, limits)Suite groups that don’t depend on functions pass
3Function library, signatures, regex, date/time and number formatting100% of the suite minus documented overrides
4Evaluation logging and auditing (tracer, audit tree, levels, annotations, explanations)Snapshot tests; under 3% overhead with the tracer off
5jlens-schema: inference, overrides, JSON Schema, static typing, completion/diagnostics/hoverTable-driven language-service tests
6Full CLICLI snapshot tests
7WebAssembly package (browser ESM), TypeScript types, web editor exampleHeadless browser tests; working demo
8Documentation consolidation, benchmarks, publishingDoc examples verified; link check green; published to crates.io and npm

0.1.0 was the first release: the engine, audits, schemas and the language service, the CLI and the WebAssembly package. 0.1.1 moved the examples, fixtures and web editor to an online store order. (0.1.0, 0.1.1)

0.2

Host functions in Rust and WebAssembly (ADR 0006), and their declarations in the language service; the web editor’s example selector. (Changelog)

0.3

A machine contract and core guardrails. The first plan after the priorities were set. It shipped the language server jlens lsp and jlens.json (ADR 0007), the CLI’s machine contract (ADR 0008): eval --json, --now and --seed, check over several files, jlens errors; and cancellation and size caps in jlens-core. (Changelog)

0.4

Catching mistakes before they run. check warns about unknown functions, wrong argument counts and types, and undeclared variables, and reads jlens.json; jlens test runs files of test cases; prebuilt binaries install with cargo binstall. (Changelog)

0.5

Safe releases, enforced limits and proven compatibility. A cap on the size of a result (U1001); the size caps, clock and seed in the WebAssembly package and the CLI; differential testing against jsonata-js (cargo xtask differential); every binary built before a release publishes anything; a security policy. (Changelog)

0.6

Bounded regular expressions, wider differential tests, signed packages. Regular expressions bounded by the timeout and cancellation (ADR 0009), on jlens-regress, a fork of regress 0.12.0; differential tests that reach regular expressions, pictures and decoders; npm provenance and build attestations for the binaries. (Changelog)

0.7

No plan of its own: three jsonata-js quirks that expose JavaScript stopped being reproduced (a regular expression applied to a value that is not a string, irregular grouping in $formatNumber, $substringBefore and $substringAfter without chars), as compatibility records. (Changelog)

0.8

Proven robustness and fast single evaluations. Coverage-guided fuzzing in a weekly workflow, and the panics, stack overflows and slow cases it found fixed; jlens lsp survives a panicking request; evaluate reads its input lazily, one level at a time (ADR 0010), and evaluate_source reads other representations. (Changelog)

0.9

Numbers and dates at the edges, and tools for the next steps. A number that overflows to infinity and a date beyond JavaScript’s range fail with D1001 where they arise; $formatNumber and $formatBase write every digit of a large number; loops over floating-point numbers end on NaN and infinity; cargo xtask fuzz-replay replays fuzz inputs on any platform. (Changelog)

0.10

Performance and robustness debts, taken as explorations that end in a fix or in the cause written down. A recursion through a higher-order function fails with D1011 instead of overflowing the stack; WebAssembly’s default maxDepth is 500; cargo xtask ab compares the speed of two revisions. (Changelog)

0.11

Faster evaluation of common shapes. A comparison with jsonata-core, another Rust port, found it 2 to 5 times faster on five cases, which eval.rs traced to work no result depends on. Each item removed one such cost, measured with cargo xtask ab and with no change to results, errors or evaluation order: field lookups on a single value, comparisons with a string literal, order-by keys evaluated once, blocks without frames, the result converted to JSON in one pass, less set-up per evaluation. jsonata-core’s second evaluator for simple expressions was left out, as two evaluators of one language can disagree. 0.11.1 made $fromMillis and $now fail with D3150 on a timezone that is not a number. (0.11.0, 0.11.1)

0.12

jlens online. The book and the web editor published on GitHub Pages at each release tag, built from the tag’s files, so that the editor runs the engine its book describes; the editor evaluates in a Web Worker, everything in the browser, and shares expressions by address. (Changelog)

0.13

Host functions that call back. A host function can call the JSONata function it receives, in Rust (HostCall::function, Callable) and in WebAssembly, within the evaluation’s limits (ADR 0011), without changing the functions written against ADR 0006. (Changelog)

0.14

More ways to install the CLI, in order of reach, each published by release.yml from the attested archives, never rebuilt: npm (jlens-cli, ADR 0012), Homebrew, Scoop and the container image ghcr.io/thkprado/jlens. (Changelog)

0.15

jlens in VS Code, and a faster CLI allocator. The extension thkprado.jlens on the Marketplace and Open VSX, with the release binary bundled (ADR 0013), and mimalloc as the allocator of the jlens command. (Changelog)

0.16

The last gaps with jsonata-core, and string literals. Measured again after 0.15.0, jlens led on seven of ten cases. Group-by stopped copying each group at every item, and paths of names, literal group keys and names mapped over many items got faster, closing the gaps. (Changelog)

0.17

A Python package. The package jlens on PyPI, in beta (ADR 0014), following the WebAssembly package: the same objects, the same errors. A path step reads its one field of an input object, and values nested thousands of levels deep no longer overflow the stack. (Changelog)

0.18

The fields an expression reads, from the expression alone (ADR 0016), in Rust, WebAssembly, Python and the CLI, for one expression or the union of several: an upper bound, exact for the paths, comparisons and aggregations rules are mostly made of, tested by evaluating each suite case on its input cut to the fields reported. JSON text is parsed without the fields no evaluation reads. (Changelog)

0.19

Closing on jsonatapy, which was faster on four of twelve Python cases. Profiles found three causes, each removed: results are written straight into Python and JavaScript values (ADR 0017); predicates of literals are evaluated once, object constructors over one item skip grouping, and $formatNumber is faster; in Python, keyword-only options, interned keys and mimalloc. (Changelog)

0.20

A deterministic step limit. The timeout reads the clock, so the same evaluation can pass on one machine and fail on another. max_steps (U1006) gives the same answer everywhere, with or without a tracer, in Rust, WebAssembly, Python and the CLI (ADR 0018); the timeout now reads the clock every 256 steps; $eval lets the limits of its text through; WebAssembly options are read without JSON. (Changelog)

0.21

Documents built from Rust values. An application that rebuilt its document often spent more on serde_json::Value and Document::new than on evaluating. Document::from_serialize builds the document straight from Rust values, and evaluate_document_with binds documents or parts of one to variables without converting them (ADR 0019). 0.21.1 published the command on npm, npx jlens-cli, once npm allowed the name of its Windows package, and 0.21.2 moved the npm packages to trusted publishing, without a token. (0.21.0, 0.21.1, 0.21.2)

0.22

Regular expressions on jlens’s own terms. jlens-regress kept as jlens’s own fork (ADR 0020), with upstream’s fixes ported; checked against V8 by a corpus of test262’s answers and a differential test, which found ten bugs; a benchmark of the engine, and a cheaper interrupt. (Changelog)

0.23

Faster lookarounds, the cases of the engine’s benchmark furthest from V8: the matcher reuses their backtracking stacks and saved groups instead of allocating them each time, halving their time. (Changelog)

0.24

Reading the application’s values faster, two costs of jlens-core that ADR 0021’s spike found. An index into a long array reads the items it picks, alone, through Source::read_item, in Rust, WebAssembly and Python, whether it is a number or held in a variable; a predicate reads its array without copying it; a group-by on a tail call applied. 0.24.1 moved the Python package to mimalloc 2 outside Windows. (0.24.0, 0.24.1)

0.25

A Java package. io.github.thkprado:jlens on Maven Central, in beta, for Java 25 and later (ADR 0021): one JAR with the libraries of seven targets, over a C API that Java calls through Panama, with a benchmark against the JVM implementations in the repository; host functions looked up when an expression names them. (Changelog)

0.26

What measuring 0.25 left open: a regression in recursion, a case slower than jsonata-js, and the cases where the JVM comparison put jlens behind. A lambda’s frame is kept in a list that shares its arguments, recursion 21 to 25% faster; $clone copies without the JSON text, the transform 40 to 52% faster; WebAssembly and Java read the fields an expression reads, in one call; Java threads find their handles without a shared lock. Every comparison runs a new copy of each build at each run, and what such a comparison can settle was measured on Windows and Linux. How it was measured is in docs/notes/perf-0.26.md. (Changelog)

0.27

What use asked for, and what 0.26 left open. Applications met variables that cost more against a Document, a quadratic $distinct and a WebAssembly package that a page opened from disk could not load. Linear where the square of the input showed: $match, $replace and $split on long texts, $distinct, $keys, $substring, & in a loop, in and the URL functions, found in use and by cargo xtask growth; variables against a Document converted as far as the expression reads them; the Java and WebAssembly packages built with link-time optimization; the WebAssembly package as one classic script, jlens.global.js; three new engines in the comparisons. How it was measured is in docs/notes/perf-0.27.md. (Changelog)

0.28

What 0.27 left in $distinct and $match, and the regex flags u and v. $distinct follows the first fields of its items into the levels below them when the items share a field or are arrays, 25 records of 100 KB that differ there 15 µs against a Document where they took 12 ms, and compares numbers and short strings inline, 100,000 items of eight values 312 µs where they took 2.2 ms; the searches of a text keep the backtracker’s storage, and matches without groups share one empty array, $match 6.5 → 4 allocations a match and regex over a long text 36% faster. The regex flags u and v, an extension that jsonata-js rejects, bring the Unicode properties and the set operations on classes; their emoji example found a bug in jlens-regress, fixed. How it was measured is in docs/notes/perf-0.28.md. (Changelog)

0.29

Completing values, and domains the application provides. The language service, which completed fields, variables, functions and operators but never a value, completes the values of an enum or const on the right of =, != and in, inside quotes too, and warns as W0206 about a literal outside a declared one; an enumeration inferred from samples is marked x-jlens-enum-inferred and never warned about. A field whose values only the application can fetch names an open domain (x-jlens-domain, or domain in the overrides), and completion returns a value request for the application to answer. The web editor gained a schema overrides panel and a “Free shipping” example that uses labels, a hidden field and an open domain; an override whose path the samples lack, often a misspelt one, is listed with the path it most likely meant. jlens_core::Offsets made public the conversion between byte and UTF-16 offsets that the Wasm package kept to itself. No evaluation code changed, and the tables moved within the floor. How it was measured is in docs/notes/perf-0.29.md. (Changelog)

0.30

Value requests with their context. 0.29’s value request said which field’s domain to fetch, but not what the expression already said about it. A request now carries its conditions: the fields compared with literals by = or in and joined to the value by and in the same predicate, read from the unfinished expression by the recovering parser, so that a domain can depend on another (categories[group = 'X' and subgroup = '| asks for the subgroups of X). It says whether the value is an element of in [...], where several may be inserted, and lists the literals the array already holds, which the application leaves out as the service leaves out declared values. The web editor’s “Open domains” example shows each. A schema override’s type takes one type name, as JSON Schema writes it, besides a list. No evaluation code changed, and the tables moved within the floor but for cases that draw one of two speeds. How it was measured is in docs/notes/perf-0.30.md. (Changelog)

0.31

A small map for objects. Every object jlens built or converted was an IndexMap, a vector and a hash table over it, though no object of the benchmark workload has more than 6 fields. 0.31 gave jlens-core a map of its own (ADR 0022): the fields in a vector, in insertion order, searched by length and then text, with a table of positions only past 8 fields, where a search in order stops being faster than hashing. Every object, tuple and $match result uses it, one allocation fewer each; two objects of one shape are compared field by field, looking a key up only from the first pair whose keys differ; and an object constructor keeps its literal keys and strings by node id for each evaluation, 2 allocations for each object where it took 6. Against 0.30.0, object constructor is 7 to 25% faster, transform 6 to 15%, tuples 7 to 14% and distinct items 5 to 21%, and the Python and Java packages 5 to 35% on those cases; nothing public changed. Before the tag, the property tests found that $merge’s T0412 showed its argument cut against a Document, as the analysis read it only needed since 0.24; it reads it whole since. The tables were measured on an Apple M1 as well, which ranks the engines the same and is quieter; from 0.32 they are measured there. How it was measured is in docs/notes/perf-0.31.md. (Changelog)

0.32

The tables on the M1, and what each node costs. The engines that compile an expression to their host’s code are 3 to 5 times faster than jlens where an expression does much work per item, and a profile of 0.31.0 put most of that time in what every node costs: the dispatch, the check of its result and the guards. 0.32 lowered that cost in jlens-core, one measured item at a time, each kept only past the floor: the stack checked by one comparison of addresses, and a source and a cancellation token by one test; a lambda’s call that reuses a frame whose scope ended unshared, and the list of arguments a call before it gave back; a variable in a lambda’s body that carries its parameter’s place; a value’s tag a word wide, which removed the stall 0.27 had found in a path step; $sum, $average, $max, $min and $count over a field of each item without the array; and the frames of a tuple stream kept for reuse, after a count showed that they, not the copies of the tuples, were most of the allocations of tuples. A profile in Node explained why WebAssembly gained little at first: there eval is now inlined into its caller. Against 0.31.0 on the M1, recursion is 35% faster natively, 30 and 34% in Python and Java and 16 to 18% in WebAssembly, the shipping rule 10 to 20%, names over items 16 to 39%, and nothing is slower; jsonata-jvm-compiler and jsonata2js stay ahead, and compiling an expression to its host’s code is not planned. The differential tests run on each item found four places where jlens and jsonata-js differ, each now told by a row of the compatibility page; one was a jsonata-js quirk copied without a row, and dropped: a position after an order-by that follows a tuple step is bound. They also led to a cycle through a transform’s copy that kept its memory after the evaluation, older than the plan and fixed, and the property tests to T0410’s value cut against a Document. Attrs gained a private field, the release’s one breaking change. From this release the performance page’s tables are measured on the Apple M1 alone, and x86_64 keeps a comparison with the release before, in the release’s notes. How it was measured is in docs/notes/perf-0.32.md. (Changelog)

0.33

Expressions checked again when their schema changes. An application that keeps expressions written against a schema another system sends it has two questions when a new version arrives: does each expression still pass the diagnostics, and did anything it uses change, even if it does? 0.33 answers both where the schema is read. The Java package gained Schema and LanguageService over the C API (ADR 0023): a schema and a service are objects by handle, shared by every thread, and the diagnostics cross as JSON text; completion, hover and signature help stay out of it. LanguageService::uses lists each path an expression reads with what the schema says there, following the analysis of the reads and not the typing, and Uses::changes compares two such answers: the paths added, removed and changed, {} when nothing the expression uses changed. The Rust crate, the WebAssembly package, the Java package and the CLI (jlens schema uses, jlens schema changes) give the same JSON, pinned by shared cases, and a host function declared to the service counts as reading its arguments alone. Two kinds of schema that jlens refused whole now load: a recursive one, whose $ref is kept as a reference by name to a definition (ADR 0024), and one whose $ref leads to another document, which the application gives by URI, as jlens never fetches (ADR 0025); a $ref that cannot be followed leaves its place unknown, and the load reports it at every end. On the way, the diagnostics were found quadratic in the fields of an object, and the load exponential in definitions that each refer twice to the next: both are bounded now. In the C API and the Java package, JSON text evaluated with host functions is cut by what the bindings read. The library of the C API grew by 17.2% on Windows, three times the estimate, of which the comparison of two answers is looked at in 0.34. jlens-core did not change, and no case of the tables moved past 3.5%. How it was measured is in docs/notes/perf-0.33.md. (Changelog)

0.34

The types the diagnostics know. The diagnostics checked a function’s arguments and the fields an expression reads, but not the operands of an operator, and not the type of a result: with total a string, total > 1000 fails with T2009 only when it runs, and a rules engine learns that a condition is not always a boolean only from the document that makes it undefined. 0.34 warns about operands whose types the operator cannot take (W0207 to W0211) and about one that may be several values (W0215: items.qty > 1 is true for an order of one item and fails for two), where the types are known and never without a schema. The typing tells a value that is always there from one that may be undefined, at the operand that makes it so, and a path that gives one value or an array from an array; built-ins are typed by their signatures and a table checked against the engine. An application declares the type a result must have, and gets W0212 (never), W0213 (another type too) or W0214 (maybe undefined), and the result’s type as a value; over the suite, 805 results proved always defined were each checked against the case’s result. An expression may be the body of a step, typed with an item as its context and the parent operator followed. The typing stopped less often at the schema: objects open to other fields, then/else, dependentSchemas, tuples and nullable read, anyOf and oneOf read as one branch or another instead of merged as allOf (found on the way, a change in what is warned), and the keywords left unread reported by the load. The result type and the context reach jlens.json, the CLI (jlens schema result), the language server, the VS Code extension and the WebAssembly and Java packages, alike on a shared fixture. Measuring found the typing had made the diagnostics up to 21% slower; a copy of the catalog of built-in functions at each call removed, they ended faster than 0.33.0’s on every case. Two date bugs of jsonata-js 2.2.2 are fixed as its open pull requests #855 and #856 fix them. jlens-core changed only in parsing a body and in the dates; the tables moved only with the M1’s newer Rust (transform 18% faster, for 0.33.0’s code as well). How it was measured is in docs/notes/perf-0.34.md. (Changelog)

0.35

The choices of 0.34 reviewed. 0.34 left choices that no one had reviewed before its release, and four of them changed. The result type and the context took the names resultType and contextPath everywhere, as result and context meant other things elsewhere, with no deprecated alias, since 0.34 had had no time to be adopted; the WebAssembly LanguageService took one object of options in place of five positional arguments, and throws a TypeError for the old form; jlens schema result kept exit code 1 on a syntax error, now documented. The items of a tuple are typed by their position, open tuple or closed, and the load reports the tuples that leave the items after them open (LoadReport::open_tuples), in every package and as one warning of the CLI and the language server. Two items were not reviews. The Java package evaluates with documents as variables (jlens_evaluate_document_with in the C API), so that two documents received as JSON text are compared with neither made into Java objects: a field of a 100,000-item table read in 0.8 µs from a document, 8.3 ms from Bindings. And jlens took three fixes of jsonata-js made after 2.2.2, ahead of its release: #861 and #841 from its main branch, from which the suite was vendored (46 cases more), and #838, approved and not merged, whose cases live in jlens-core’s tests; the differential test runs against a checkout of jsonata-js too (--jsonata-js). Measuring #7 found that the variables of an evaluation went on the list of frames that may be part of a cycle: off it, an array or object as a variable costs about 15 ns less in every package. Nothing in the tables moved past 2.6% slower; recursion is 6 to 8% faster natively. How it was measured is in docs/notes/perf-0.35.md. (Changelog)

0.36

What adoption asks. jlens had its first users outside its own repository, and the plan took what they asked for. W0215 tells an operand that is always an array from one that may be several values, and its hint writes the expression with in, as the old hint taken to the letter gave another wrong one. For an application in Java that evaluates large documents from a pool of threads, the native memory of a document was measured at its peak and while it lives, the C API took the package’s buffer as the document’s text, so that a document needs its text’s memory once while it is made (a 16 MB document’s peak from 150 to 133 MB), and the Java guide says what a document costs per thread. jlens-regress got a version of its own, 0.35.1, raised only when the crate changes, with searches of UTF-16 and UCS-2 text that an interrupt stops, for a crate that uses it alone; it took the 20 commits of regress after 95c0404. Releases got a cadence, a minor every two or three weeks, and their channels two tiers. Most of the plan followed jsonata-js: three of 2.2.2’s bugs reported after its main’s 6d9d829, then its main branch as it moved, $formatNumber from the shortest decimal digits (#868), a regular expression that starts a block (#860), the date/time pictures rewritten (#869), with $toMillis matching in linear time and no picture running past an evaluation’s timeout, and transforms and ** (#870, #871, #873). jsonata-js 2.3.0 was released during the plan, with those fixes, and became the behaviour target in place of 2.2.2; the section “Next: the jsonata-js release after 2.2.2” left the roadmap, its item done. Its template strings («...») are the one feature jlens lacks: of 2.3.0’s 1,972 cases, jlens passes 1,901. An outside review of the code found six gaps, fixed with tests (JSON text read 1,000 levels deep, $formatNumber with a long grouped picture in linear time, the host’s $clone under a name no expression can bind, among them), and four more items for 0.37. Two items moved to 0.37 to wait for the Java adoption: a result kept as a Document, and ADR 0015. In the tables, number formatting takes 4 to 32% less in every package and $toMillis with a picture 62 to 67% less; a field #18 added to the evaluator slowed Python’s object constructor in some environments, and #21 removed it. The release’s check on x86_64 found nothing to change. How it was measured is in docs/notes/perf-0.36.md. (Changelog)

0.37

What adopters need before they evaluate. The applications adopting jlens were to judge it with this plan, so it took what they would meet first. Template strings («Hello {name}!»), the one feature of jsonata-js 2.3.0 that 0.36 left out, are read as 2.3.0 reads them, and jlens passes 1,970 of the 1,972 cases of its suite; the other two are documented differences. For editors built on jlens, the language service lists a schema’s fields with what completion and hover know of them and their own x- keywords, after the JSON Schema reader’s gaps that the list would show were fixed (required in allOf, beside a $ref or alone, closed tuples). From the two lists, an application builds a table of paths when a schema’s new version renames or moves fields, and rename rewrites the expressions stored against the old one, the rest of the text kept, with the places it cannot be sure of; a second outside review, of the code at 285e0b7, found where that rewrite could change what an expression means, fixed before the release. An outside review of the code at 7b69a6e gave the fixes: the size limits stop a result while it is built ($replace, $split, $match, $pad, $fromMillis, and a filter that repeats a position), a regular expression literal is compiled once per expression (regex 7 to 18% faster on every platform, $toMillis of an ISO text 88%), the Java package holds up under threads and failures (a document’s conversions swept, no critical downcall, Options that evict), and the Python package calls no method of its input’s values while it holds their lock. jlens-regress 0.35.2 keeps the searches of &str fast under its utf16 feature, which had made them up to 128 times slower, with four more commits of regress. New fuzz targets cover what applications send to the language service; the workflows pin their actions by commit, and the release workflow drafts the GitHub release once the libraries are published, without waiting for the tools’ channels. The WebAssembly guide says how to serve the module under a Content-Security-Policy, and what the module is made of was measured for 0.38’s ADR: without the language service it is a quarter smaller. Three items moved to 0.38: a result kept as a Document, ADR 0015 and a binding of a block’s predicate. The release’s check on x86_64 found nothing to change. How it was measured is in docs/notes/perf-0.37.md. (Changelog)

Conformance testing

jlens vendors the language-neutral test suite of the reference implementation (jsonata-js, MIT) in tests/jsonata-suite/, from its tag v2.3.0. The suite has 103 groups and 1,972 cases. The harness lives in crates/jlens-core/tests/conformance.rs and mirrors test/run-test-suite.js:

  • Each case is one test, named <group>/<file>, or <group>/<file>#<index> for files that hold an array of cases.
  • The input comes from data. If there is no data, the input is the named dataset; "dataset": null means undefined input.
  • timelimit and depth map to Options::timeout and Options::max_depth.
  • Each case states exactly one expectation:
    • result, compared with deep equality where numbers compare as JavaScript numbers, so 1 equals 1.0;
    • undefinedResult;
    • code, optionally with token;
    • error, an object whose fields must all match.

The baseline ratchet

tests/conformance/baseline.txt lists the cases that must pass, and cargo test fails only if one of them regresses. Every other case is reported as ignored. To work on a group, run it with:

cargo test -p jlens-core --test conformance -- --include-ignored array-constructor/

To measure progress and lock in new passes:

cargo xtask conformance                    # writes tests/conformance/REPORT.md
cargo xtask conformance --update-baseline  # also rewrites baseline.txt

Overrides

tests/conformance/overrides.json records every intentional deviation. Each entry needs a reason and may skip the case, or replace its expectation with alternateResult or alternateCode. The current overrides are:

CaseReason
function-encodeUrl/case002, function-encodeUrlComponent/case002The data contains a lone UTF-16 surrogate (U+D800), which Rust’s UTF-8 strings cannot represent.
boolean-expresssions/issue765#10 to #131e308 * 10 overflows to infinity: jlens fails with D1001 at the *, jsonata-js at the and or or that converts the infinity to a boolean. The code is the same, the token and position are not.
function-fromMillis/issue853#30 and #31A date beyond JavaScript’s range: jlens fails with D1001, where jsonata-js writes each component as NaN.

Property tests

The suite checks that jlens gives the right answers. Property tests (proptest) check that no input makes it crash, whatever the input:

TestWhat it generatesWhat must hold
jlens-core/tests/robustness.rsValid expressions from a small grammar, near-valid token soups, and arbitrary stringsParsing (strict and recovering), evaluation, evaluation against a Document, and audited evaluation never panic; diagnostic spans stay inside the source
jlens-schema/tests/robustness.rsToken soups and arbitrary stringsCompletion, diagnostics, hover and signature help never panic at any byte offset; ranges stay inside the text

They run 2,000 and 1,000 cases with cargo test. Set PROPTEST_CASES for longer runs: PROPTEST_CASES=100000 cargo test -p jlens-core --test robustness.

The property tests found two bugs:

  • In recovering parsing, an out-of-range number (1e310) looped forever.
  • A transform such as |items|{'p': $}| built an object containing itself, which then overflowed the stack when converted to JSON. It now fails with U1001.

Both have regression tests.

Fuzzing

Property tests draw their inputs at random. Coverage-guided fuzzing (cargo-fuzz, with libFuzzer) keeps the inputs that reach new code and mutates them, so it finds the paths that random inputs rarely reach. The targets live in fuzz/, a crate outside the workspace:

TargetInputWhat must hold
parseAn expressionStrict parsing never panics
parse_recoverAn expressionRecovering parsing never panics; diagnostic spans stay inside the source
evaluateAn expression, optionally followed by a NUL byte and a JSON input documentCompiling, then evaluating with and without input, against a Document and audited, never panics
regexA byte of flags, then a pattern and a text separated by a NUL byteCompiling the pattern with jlens-regress and finding every match never panic; groups lie on character boundaries of the text
picturesA picture, optionally followed by a NUL byte and a second string$formatNumber, $formatInteger, $parseInteger, $fromMillis and $toMillis never panic on the picture, the text they parse or the time zone
language_serviceTwo bytes of offset, then a textDiagnostics, completion, hover and signature help never panic, at any offset, against an inferred schema and a recursive one with a $ref left unresolved; their ranges lie inside the text. What a text that compiles uses of each schema reads back from its JSON form, and has no change against itself
json_schemaA JSON documentRead as a JSON Schema (which also refers to itself under another URI) and as a sample to infer a schema from, it never makes the reader panic. What is written back reads again, and reads as itself the second time. The listed fields read back from their JSON form, and the service knows each listed path: no W0201 warning
parse_cutAn expression, optionally followed by a NUL byte and the JSON text of the inputParsing the text cut by what the expression reads never panics. Where Document::parse accepts the text, the cut document is the value cut, and the expression gives the same result or error code on it as on the whole document
renameAn expression, then optionally a NUL byte and a JSON input document, and a NUL byte and a table of renames, an old path’s line followed by its new one’sRenaming never panics. An empty table gives the text back. The edits, in order, make the text, and the text parses. Renaming every field the expression reads, when no place is unsure, gives the same result or error code on the input with its keys renamed, unless the result holds an object

Evaluations run with a timeout, a depth limit, size caps, and a fixed clock and seed. Each target runs on a thread with a 1 MB stack, the size of the main thread’s stack on Windows, so that recursion that does not grow the stack overflows on Linux too. The build has debug assertions, so an arithmetic overflow is a crash.

The Fuzz workflow runs every target for ten minutes each week, or for as long as asked when started by hand. Each target starts from seeds that cargo xtask fuzz-seed writes to fuzz/corpus/: the expressions and input documents of the JSONata suite, a few regular expressions and pictures, and the JSON Schemas and rename tables of fixtures/. It also starts from the corpus its last run kept. A crash fails the run, and the input that caused it is uploaded with the run, along with the corpus. A stack overflow stops the target before libFuzzer can write the input; the targets write each input to the file that JLENS_FUZZ_LAST_INPUT names before running it, and the workflow uploads that file as last-input.

cargo-fuzz needs nightly Rust and Linux or macOS. To fuzz, on Linux:

cargo install cargo-fuzz
cargo xtask fuzz-seed
cargo +nightly fuzz run evaluate --sanitizer none --debug-assertions

The bodies of the targets live in fuzz/src/targets.rs, apart from libFuzzer. To reproduce a crash on any platform, with stable Rust, replay the saved input, such as the last-input or crash-* file of a failed run, or a whole directory of them, such as a corpus:

cargo xtask fuzz-replay evaluate fuzz-evaluate/last-input
cargo xtask fuzz-replay parse fuzz/corpus/parse

The replay runs each input through the target’s body on the same 1 MB thread, in an optimized build with debug assertions, as the workflow does. It prints the path of each input before running it, so the last path printed names the input of a stack overflow, which stops the program; a panic is reported and the next input runs.

Each crash becomes an ordinary test in the crate where the bug was, which runs with cargo test on every platform.

Two early crashes left no input: stack overflows in pictures (run 38159469720) and in parse (run 38158412916), both before the targets wrote last-input. In October 2026 every input the failed runs kept was replayed: their corpora (45,148 parse and 17,703 pictures inputs), their last-input and crash-* files, and the seeds of every target. None crashes. The cached corpora cannot be downloaded, but each run executes its whole corpus before fuzzing, and the run of 0.9.0 (38225748988) did so for all six targets without a crash. Both crashes most likely had causes fixed since, which later runs found with an input: numbers in words recursing on the NaN day that pictures began to produce in the commit of its crash, and a lambda body whose tail calls were marked without growing the stack. They are not tracked further.

Differential testing

The suite covers the cases its authors thought of. Differential testing covers others: it generates expressions and runs them in jlens and in jsonata-js 2.3.0, which must agree on the result or, when the expression fails, on the error code.

(cd benches/compare && npm install)
cargo xtask differential                     # 1,000 cases, from a seed it prints
cargo xtask differential --cases 10000 --seed 42
cargo xtask differential --jsonata-js ../jsonata   # a checkout of jsonata-js, run from its sources

The expressions come from a grammar like that of the property tests, without the functions that read the clock or draw random numbers. The grammar also calls the functions that were hardest to port with meaningful arguments: regular expression literals for $match, $replace, $split, $contains and ~>, valid pictures for $formatNumber, $formatInteger and $fromMillis, round trips through $parseInteger, $toMillis and the decoders. Names are bound in blocks, in the body of a lambda with no block around them, which binds in the frame of the call, and in array and object constructors, and read afterwards. Each case runs against one of a few input documents, or none, and in jlens also against a Document, which reads its variables another way and must give the same outcome. The command writes the cases to target/differential/cases.json. benches/compare/differential.mjs runs them in jsonata-js. The command then compares each outcome with that of jlens. Results are compared as JSON, with numbers compared as values and the keys of an object in order. Both engines run with a timeout and a depth limit, and a case that reaches either limit is skipped. The divergences are printed and written to target/differential/divergences.json. The command fails when there are any. A seed reproduces a run.

Twelve kinds of disagreement are known differences of jsonata-js, listed in the compatibility notes. They are not divergences; the command counts them apart:

  • Order of integer keys: the results differ only in where an object has its keys. JavaScript puts the keys that are integers first, ascending; jlens keeps the order of insertion.
  • jsonata-js crashed: it threw a JavaScript exception, which has no error code to compare.
  • jsonata-js hung: the case ran for ten times the timeout, or ran out of memory, in a synchronous loop that the jsonata-js timeout cannot interrupt ($match('abc', /b/) ?? 1). The runner evaluates the cases in a worker thread, stops it, and goes on with the next case in a new one.
  • jsonata-js split a character: a string of the jsonata-js result holds a lone surrogate, half of a character outside the Basic Multilingual Plane, which a jlens string cannot hold. A JavaScript regular expression without the u flag matches UTF-16 code units, so $match('a𝄞', /[^a]/) matches the first half of 𝄞; jlens matches the whole character. The halves need not reach the result ($replace('𝄞', /[^a]/, '-') is -- in jsonata-js, - in jlens), so a case whose outcomes differ counts here too when it has such a character, in its expression or input, and a pattern that may match half of one: a negated class, ., \S, \W, \D, \B, or a quantifier that may match the empty string.
  • Regex left of ?? or ?:: the outcomes differ, and the expression has a regular expression literal on the left of ?? or ?:. The jsonata-js parser copies that side through JSON, which turns the regex into {}, so the expression hangs (counted above) or gives another result.
  • Concurrent errors: both engines failed with different codes, and the expression has an array constructor with several items or an object constructor. jsonata-js evaluates those parts concurrently, so when two of them fail it reports whichever fails first in its asynchronous schedule. jlens reports the first in source order.
  • Name shared by concurrent items: the outcomes differ, and one item of an array constructor, or one value of an object constructor, binds in their frame a name that another reads or binds. In jsonata-js what the other sees depends on how many asynchronous steps each takes (($x := 1; [$x := 5, $x]) is [5, 1], and [5, 5] with 0 + $x). jlens evaluates them in order.
  • jsonata-js changed its input: the jsonata-js runner saw the input document change during the evaluation (a group-by on an empty array adds an item to it), or saw a group-by add that item to an empty array it did not create, a variable’s or an item of a value the expression built (([1, []])^(({}; 1)) is [1, [null]]), and the outcomes differ.
  • Sequence as context: the expression has a wildcard, and the jsonata-js result is jlens’s with true items added. An array that jsonata-js builds from a path carries an own property sequence: true, which its wildcard enumerates with the items. Without a context, the flag can change a result without appearing in it: a path whose first step is an array constructor evaluates it on the sequence [undefined], so [*].price is undefined in jsonata-js, which went on with [undefined, true], and [] in jlens. A $not() there takes the sequence for its argument and gives true, so [$not()].a is undefined in jsonata-js and [] in jlens. The context is undefined without an input, and with one in a predicate on nothing, which both engines evaluate once (nothing[1 * [*].price]). A case whose expression has such a path counts here whatever the outcomes.
  • Dropped quirk: the expression may meet a jsonata-js quirk that jlens does not reproduce: a regular expression literal applied with ~> to anything but a string literal, $substringBefore / $substringAfter whose chars is not a string literal, $replace whose replacement is neither a string literal nor a lambda, $fromMillis with a computed picture, which may hold a marker with an unknown component and a presentation, or a left side of ?? or ?: that binds a name it reads, which jsonata-js evaluates twice ($count($x := [$x, 1]) ?: 0).
  • Overflow to infinity: jlens failed with D1001, which it raises only where a number overflows to infinity (1 / 0). jsonata-js passes the infinity on, to its result or to an operator that fails later.
  • Exact digits of $formatBase: from 2^53, in a radix that is not a power of two, where jsonata-js writes zeros for the digits below the number’s precision.

The Differential workflow runs 20,000 cases from a new seed every week, and on demand with a chosen number of cases and seed. When it fails, the cases and outcomes are attached to the run.

The regular expression engine

The suite and the differential test reach jlens-regress only through JSONata, with the patterns their expressions happen to hold. The engine has its own judge: a corpus of V8’s answers in crates/jlens-regress/tests/corpus/v8.json, which cargo test runs. Each case compiles a pattern, which V8 accepted or rejected, or runs one exec: the pattern, the flags, the input, lastIndex, and V8’s match with the ranges of its groups, in UTF-16 code units.

cargo xtask regex-corpus          # rebuild it from the test262 commit it came from
cargo xtask regex-corpus main     # or from test262's latest commit

The command fetches test262’s built-ins/RegExp and annexB/built-ins/RegExp tests into target/test262 and runs each in a fresh Node.js realm, whose RegExp.prototype.exec and RegExp constructor record their calls. test, match, replace, split and the other methods all go through exec, and whether a test passes does not matter, only what it calls. The negative syntax tests contribute their literal. It also records the patterns and searches of the crate’s own tests (JLENS_REGRESS_RECORD). Then V8 answers each call in a realm nobody touched. A loop over every code point with one pattern is sampled: every rare answer is kept, and an even sample of the common ones.

The test runs the cases as jlens does, with find_from_interruptible on a &str. A case with a lone surrogate, or whose match starts or ends inside a surrogate pair, is counted and skipped: a &str cannot hold it. Any other difference fails the test unless tests/corpus/differences.txt lists it with its reason, and a listed case that agrees again fails it too.

The corpus holds the patterns that test262’s authors wrote. A differential test generates others, and compares the engine with V8 on them:

cargo xtask regex-differential                     # 1,000 patterns, from a seed it prints
cargo xtask regex-differential --cases 20000 --seed 42

The patterns come from the grammar of ECMAScript’s regular expressions: alternatives, quantifiers (lazy, and some out of order), groups (capturing, named with names that repeat, non-capturing, with modifiers such as (?-i:...)), lookarounds, backreferences (to groups that exist, come later or do not exist), classes with ranges and escapes, set operations and \q{...} with the v flag, property escapes, and pieces that only Annex B accepts or nothing does. Their characters are those whose case folding differs between the modes (the Kelvin sign, the long s, the dotless and dotted i, ß and ẞ, the sigmas), line terminators, spaces, and characters outside the BMP. Most have neither u nor v, as jsonata-js compiles every pattern; about half have i. Each pattern searches three inputs drawn from the characters it names. The command writes the cases to target/regex-differential/cases.json, and crates/jlens-regress/tests/differential.mjs runs them in Node.js 24 or later, under a timeout. Both engines search each input as String.prototype.matchAll does, up to 20 matches. Whether the pattern compiles, and every match with the ranges of its groups in UTF-16 code units, must agree. The divergences are printed and written to target/regex-differential/divergences.json, and the command fails when there are any.

Four kinds of disagreement are counted apart:

  • V8 timed out, or jlens-regress was interrupted: a search did not finish within a second in V8, or within about ten million backtracking steps in jlens-regress.
  • UTF-16 code units: without u or v, the case has a character outside the BMP, which V8 matches as two code units and jlens-regress as one character. The pattern may write it as a surrogate pair of escapes, 𝄞, which V8 reads as two characters: in a class, [-𝄞] is then a range out of order. A search that V8 would go on inside a surrogate pair is compared up to there.
  • Known V8 bugs, where jlens-regress follows the specification, each recorded in the corpus: two groups of the same name that both take part in a match, which V8 accepts when one is in an alternative of a group the other is not in; a group that changes the i flag, around which V8 folds case wrongly in places; and, with the flags v and i, \p{ASCII} and the strings of \q{...}, which V8 does not always fold.

The Differential workflow runs 20,000 patterns from a new seed every week, next to the JSONata expressions. Its first runs found ten bugs in the engine, among them the case folding of ı, ſ and the Kelvin sign without u, which jsonata-js patterns reach; they are fixed, and tests/v8_differential.rs keeps them in the corpus.

Performance

jlens is a tree-walking interpreter, like jsonata-js. This chapter says how fast it is against the other JSONata engines on each platform, how that is measured, and how to use the API to get the most from it.

Summary

Measured for 0.37.0 on an Apple M1 (below), on seventeen expressions over a 24 KB order and an array of 10,000 items:

PlatformAgainst the referenceAgainst the fastest other engine
Rustcustomer.name in 0.10 µs, a 30-line rule in 42 µs against a Document–
Node.js (WebAssembly)faster than jsonata-js on 15 of 17 cases with evaluate, all 17 against a Document, by up to 520×jsonata2js, which compiles to JavaScript, is faster on 14 of 17
Pythonfastest of the Python packages on 14 of 17 cases with Python values, 15 of 17 against a Document; 18 to 226× jsonata-pythonjsonata2py leads on names over items and the index into 10,000 items, jsonatapy on that index once converted
Javafaster than jsonata-java on all 17 cases against a Document, the most evaluations per second from JSON text on any number of threadsjsonata-jvm-compiler, which compiles to bytecode, is faster on most cases over converted input
  • jlens is fastest where the expression reads a little of a large input (an index, a path) and where an input converted once into a Document serves many evaluations.
  • The engines that compile an expression to the host language’s code (jsonata2js, jsonata2py, jsonata-jvm-compiler) are faster on most cases that do much work per item. jlens is an interpreter, and the same on every platform.
  • On deep, cyclic or endless input, jlens fails with a JSONata error code and never ends the process (Python, Java).

The numbers are meant for comparing alternatives on one machine. They are not guarantees, and your hardware will give different absolute values. How each change was measured (methods, traps, intermediate numbers) is kept outside the book, in docs/notes/: perf-0.37.md, perf-0.36.md, perf-0.35.md, perf-0.34.md, perf-0.33.md, perf-0.32.md, perf-0.31.md, perf-0.30.md, perf-0.29.md, perf-0.28.md, perf-0.27.md, perf-0.26.md and perf-earlier.md.

Benchmarks

The workload is in benches/ at the repository root. It is shared by the native benchmarks and by the comparisons with jsonata-js, with the other Python packages and with the JVM implementations:

  • benches/cases.json lists seventeen expressions: path navigation, a name mapped over the items, filters with aggregation, grouping, sorting, string and regex functions, number formatting, an object constructor, a transform, a recursive function, the shipping rule from the guides, two indexes into a long array (one of them held in a variable), a regex over a 20 KB text, $distinct over the items, and a path with tuples.
  • benches/orders-200.json is a 24 KB store order with 200 items, the input of most cases.
  • benches/items-10000.json is an array of 10,000 small items, the input of the two index cases, items[0].code and ($i := 0; items[$i].code): they cost little only when an index does not touch the other items, which 200 items would hide.
  • benches/growth.json lists the cases of cargo xtask growth, which times each built-in function and operator at 1,000 to 64,000 items and prints the exponent of its growth, 1 for linear and 2 for quadratic (where the time goes).
  • crates/jlens-core/benches/host_state.rs builds a document from Rust values again and again, as an application that keeps its state in Rust types does (below). It is native only.
cargo bench -p jlens-core                     # criterion, native
cargo xtask bench-table                       # the native table below: the median of three runs
cargo xtask ab main .                         # two revisions against each other, native
cargo xtask wasm && cd benches/compare && npm install && node compare.mjs   # against jsonata-js
python benches/compare/python.py speed jlens=<python> ...   # against the Python packages
python benches/compare/python.py ab A=<python> B=<python>   # two builds of the Python package
cargo xtask java-compare                      # against the JVM implementations (benches/compare/README.md)
cargo xtask java-compare ab <A.jar> <B.jar>   # two builds of the Java package
cargo bench -p jlens-regress --bench engine   # the regular expression engine alone (below)
cargo xtask growth                            # how each built-in's time grows with its input

The numbers below were measured for jlens 0.37.0 on a MacBook Air M1 (4+4 cores, 16 GB, no fan) under macOS 27, with Rust 1.100, Node.js 24, Python 3.14.10 and OpenJDK 25.0.5.1; the system’s thermal pressure stayed nominal through the runs. The columns of other engines whose version has not changed keep the numbers measured there for 0.31.0, the first release measured on it, or for the release that measured their version first.

A table that names an earlier release was measured for that release on an AMD Ryzen 7 3700X under Windows 11 (Linux: Ubuntu 26.04 under WSL 2), where every table up to 0.30.0 came from, and is not measured again: its absolute times are about twice the M1’s. x86_64 has no tables of its own. A release whose plan changed the evaluation is compared with the release before it on that machine, natively and in Python under Linux, and what that finds is in the release’s notes.

Comparing two revisions

To measure a change, compare the revision before it with the revision that makes it. Criterion alone can mislead here: on some machines its results are bimodal, so two runs of one build can differ by more than the change. cargo xtask ab is built for this:

cargo xtask ab main .                         # main against the working tree
cargo xtask ab v0.9.0 HEAD --case regex --case strings --rounds 20
cargo xtask ab main . --mode document         # evaluate_document instead of evaluate
cargo xtask ab main . --mode source           # evaluate_source instead of evaluate
  • A revision is anything git names, or . for the working tree. Each is built once with the release profile, in a temporary worktree, and kept in target/ab/bin.
  • --mode picks how the cases read their input: a serde_json::Value (evaluate, the default), a Document converted beforehand (document), or a Source written in the program, one level at a time, as the Python and Java packages read their values (source).
  • It runs the two programs in alternation, ten rounds by default (--rounds), A then B, then B then A, so that a drift of the machine reaches both, each on a new copy of its program. It prints the median of the rounds for each case and how much slower B is. Judge by the median.
  • Run one comparison at a time: two at once disturb each other, by 8% on the Ryzen.

A time also follows the memory a program’s code was given, which stays with a file while it is cached: six copies of one program differed by up to 5.6% on Windows, and by 10% on one case under Linux. The new copy for each round turns that into spread, and a revision compared with itself shows the floor of a comparison: most cases within 1.7%, the transform within 2.9% and the object constructor within 4.1% on Windows; within 2.6% under Linux; within 0.8% on the M1.

Code placement moves cases too: a change can make a case that runs none of its code 5 to 8% slower or faster, as the release profile (LTO, one codegen unit) lays the whole program out again. To set that aside, build both programs with functions and blocks aligned, as the engine’s benchmark does, through RUSTFLAGS; ab names its programs by commit, not flags, so delete the commit’s program before an aligned run and after it.

The Python and Java packages are compared the same way with python.py ab and cargo xtask java-compare ab, five rounds by default. * marks a difference on which no run of one build reaches the other’s, above 3.5% in Python and 5% in Java (benches/compare/README.md). The tables below come from one build each, so a change of a few percent from an earlier table can be that build’s; the release compares builds as above (0.37 against 0.36.0).

Native (criterion)

The table is measured with cargo xtask bench-table, in about ten minutes. It builds the program of cargo bench -p jlens-core --bench evaluate once, with the release profile and no alignment flags, as an application builds it, runs a new copy of it three times, and prints each case’s time in each run and their median. A case where most runs are more than 2% from the median, or whose runs fall in two groups more than 5% apart, is marked and run again with --runs 5. A case more than 2% away from the previous table is compared with cargo xtask ab <previous tag> ., built aligned, before the difference is put down to a change.

Each evaluate call reads its serde_json::Value input as the expression reaches it, one object or array at a time (ADR 0010); evaluate_document evaluates against a Document converted beforehand. With macOS’s system allocator:

Caseevaluateevaluate_document
path (customer.name)0.24 µs0.10 µs
names over items ($sum(items.quantity))7.0 µs1.71 µs
filter + aggregate26 µs17.2 µs
group-by48 µs39 µs
sort + map165 µs148 µs
strings42 µs32 µs
regex59 µs50 µs
number formatting12.3 µs11.0 µs
object constructor85 µs75 µs
transform189 µs169 µs
recursion ($f(15), Fibonacci)232 µs233 µs
shipping rule60 µs42 µs
index into 10,000 items (items[0].code)0.52 µs0.29 µs
index in a variable (($i := 0; items[$i].code))0.66 µs0.41 µs
regex over a long text (20 KB)88 µs87 µs
distinct items50 µs10.7 µs
tuples (items#$n@$i[...])76 µs68 µs

Three copies, which agreed within 1.9% (recursion with evaluate, group-by against a Document). On Windows, the system allocator makes some cases draw one of two times for each process (recursion against a Document 776 or 890 µs on the Ryzen); mimalloc, which the command and the packages use, does not draw.

Other measurementsTime
Compile customer.name0.64 µs
Compile the shipping rule (30 lines)21 µs
Document::parse of the 24 KB document66 µs
Document::new from a serde_json::Value38 µs
serde_json::from_str of the same text, for reference114 µs
Shipping rule, audit level decisions770 µs (13× without a tracer)
Shipping rule, audit level full3.73 ms (62× without a tracer)

Without a tracer, evaluation takes the shortcuts described under Where the time goes; with one it takes the general path, so that the audit reports every node, hence the large ratios.

The path case reads one field of the input, customer, and one of that object, name: evaluate takes 0.24 µs, where converting the whole input first took 38 µs. A path step reads only the field it looks up (ADR 0010, amended), so names over items reads one field of each item and takes 7.0 µs. An expression that reads whole items pays for converting them, and the allocator sets much of that cost; an application that calls evaluate on whole documents can set a faster global allocator, as the jlens command does.

The allocator of the command

Evaluation allocates for most of its work, so the allocator sets much of its speed. The jlens command uses mimalloc as its global allocator on every release target, and so do the Python and Java packages. cargo xtask ab . . --b-allocator mimalloc measures the allocator alone (B is the same revision with mimalloc), and --target x86_64-unknown-linux-musl builds both programs for musl, as the Linux release binaries are. Measured for 0.17 on the Ryzen with evaluate: musl’s own allocator is the slowest of the three, up to 5.6 times a glibc build, and mimalloc makes it 28 to 67% faster; on Windows, mimalloc saves 17 to 52% (the transform 1.18 ms against 604 µs); glibc’s allocator is the fastest, and mimalloc still saves 3 to 20% on ten cases of twelve. On macOS, the system allocator was not compared with it. Until 0.26, every evaluation on musl’s main thread ran on a new stack segment (stacker#155); jlens works around it, and path takes 339 ns there with mimalloc.

WebAssembly against the other engines (Node.js)

All run in the same Node.js process, on the same input. The WebAssembly module is the release build optimized by wasm-opt -Os, with link-time optimization since 0.27. The comparison script first checks that each engine gives jsonata-js’s result for each case, and all do. The jsonata-js times include the await that its asynchronous evaluate requires. jsonata2js translates an expression to JavaScript source and lets the JavaScript engine compile it. benches/compare/README.md says how each is called.

Measured for 0.37.0, the median of four runs, each on a new copy of the module, which agreed within 3%, but jsonata-js, up to 7% apart on recursion, and the times under 4 µs, printed to a tenth; jsonata2js for 0.31.0, as its version has not changed since. jsonata-js 2.3.0 is within 2.3% of its numbers for 0.36.0:

Casejsonata-js 2.3.0jsonata2js 0.1.2jlens-wasm evaluatejlens-wasm evaluateJsonjlens-wasm evaluateDocument
path1.3 µs0.2 µs2.4 µs72 µs0.7 µs
names over items42 µs3.2 µs29 µs101 µs3.7 µs
filter + aggregate417 µs8.8 µs87 µs146 µs27 µs
group-by649 µs13.8 µs125 µs175 µs55 µs
sort + map3.00 ms61 µs292 µs353 µs236 µs
strings372 µs11.1 µs127 µs190 µs53 µs
regex381 µs10.1 µs118 µs182 µs77 µs
number formatting336 µs75 µs42 µs124 µs16.9 µs
object constructor753 µs52 µs151 µs282 µs87 µs
transform819 µs204 µs354 µs496 µs191 µs
recursion5.59 ms42 µs365 µs430 µs358 µs
shipping rule1.12 ms27 µs194 µs205 µs65 µs
index into 10,000 items1.3 µs145 µs3.4 µs2.31 ms0.9 µs
index in a variable1.97 ms197 µs3.8 µs2.31 ms1.1 µs
regex over a long text346 µs135 µs184 µs184 µs158 µs
distinct items6.47 ms56 µs178 µs167 µs16.7 µs
tuples652 µs28 µs155 µs215 µs95 µs
  • evaluate is faster than jsonata-js on fifteen of the seventeen cases, by up to 15× on recursion, 36× on distinct items, whose $distinct is quadratic in jsonata-js, and 520× on the index held in a variable, which jsonata-js tests against every item. It is slower on path and the index into 10,000 items, which do almost no work, so the overhead of calling into WebAssembly dominates.
  • Against a Document converted once, jlens-wasm is faster than jsonata-js on all seventeen cases: by 12 to 20× on recursion, group-by, sort + map, filter + aggregate, number formatting and the shipping rule, 390× on distinct items, 4.3× on the transform and 1.4× on the index into 10,000 items.
  • jsonata2js is faster than evaluate on fourteen of the seventeen cases, and than evaluateDocument on twelve: by 1.2 times on names over items and regex over a long text to 8.5 times on recursion. As compiled JavaScript, it reads the JavaScript objects it is given, with nothing to convert. jlens-wasm is faster on number formatting, the two indexes into 10,000 items, and, against a Document, distinct items and the transform. Called again on the same text, its compile takes 2 to 4 times what jlens’s new Expression takes, which it makes up within a few evaluations.
  • jsonata-js works on the JavaScript objects it is given, with nothing to convert. jlens-wasm evaluate reads the input object as the expression reaches it: up to 16 values in one call to a JavaScript helper, a long array of objects in one call with the fields the expression reads, and an index the items it picks alone. An expression that reads every item whole pays what converting the whole input does: JSON.stringify takes 27 µs, parsing it into a Document 136 µs.
  • evaluateJson takes JSON text and returns JSON text, and parses the input without the fields the expression does not read (ADR 0016). Parsing still costs far more than a small evaluation: 72 µs on path, and 2.3 ms for the text of 10,000 items. An input evaluated more than once is best converted once into a Document.

gnata-js 0.6.2, the Go engine gnata built for WebAssembly, left the table after 0.27.0: it was slower than jlens-wasm on every case.

Python against the other implementations

benches/compare/python.py compares the Python package with three other JSONata packages on PyPI: jsonatapy, the Python package of jsonata-core, a JSONata engine in Rust; jsonata2py, which translates an expression to Python source and compiles it; and jsonata-python, a port of jsonata-java in pure Python, by far the most downloaded. Each package needs a virtual environment of its own, as several install a module named jsonata; the script’s docstring says how to run it. Each package gives jlens’s result on each case but regex over a long text, where jsonata2py and jsonata-python give 4,150, not the 9,858 of jsonata-js and jlens: Python’s \w matches the accented, Greek and Japanese letters that JavaScript’s does not.

Measured for 0.37.0, on Python 3.14.10; jsonata2py for 0.31.0, as its version has not changed since. jsonatapy 2.2.17 was built from its source distribution when installed. The input is the document as Python values, and for jlens and jsonatapy also an input converted once (Document, JsonataData). jlens and jsonatapy are the median of three runs, which agreed within 2.5%, but jsonatapy 5.4% apart on the transform converted once; jsonata-python, one run, within 1.4% of its numbers for 0.36.0. jsonatapy 2.2.17 is within 3.5% of 2.2.15 but on the transform, 29% faster (724 → 511 µs):

Casejsonata-python 0.7.2jsonatapy 2.2.17jsonatapy, JsonataDatajsonata2py 0.1.3jlens evaluatejlens evaluate_document
path1.06 ms0.5 µs0.2 µs0.5 µs0.5 µs0.4 µs
names over items1.40 ms15.0 µs3.6 µs13.2 µs13.7 µs2.0 µs
filter + aggregate3.28 ms58 µs35 µs62 µs38 µs17.3 µs
group-by4.68 ms88 µs60 µs151 µs68 µs38 µs
sort + map17.4 ms302 µs226 µs266 µs170 µs128 µs
strings3.10 ms81 µs54 µs64 µs49 µs28 µs
regex3.24 ms91 µs73 µs158 µs59 µs43 µs
number formatting2.85 ms70 µs67 µs90 µs12.6 µs9.6 µs
object constructor4.11 ms155 µs124 µs182 µs87 µs60 µs
transform3.92 ms511 µs429 µs347 µs204 µs132 µs
recursion28.8 ms593 µs593 µs1.39 ms233 µs233 µs
shipping rule7.03 ms166 µs100 µs221 µs100 µs42 µs
index into 10,000 items20.3 ms183 µs0.4 µs0.7 µs0.8 µs0.5 µs
index in a variable36.2 ms625 µs440 µs1.29 ms0.9 µs0.6 µs
regex over a long textdiffers93 µs94 µsdiffers88 µs88 µs
distinct items1.46 ms511 µs410 µs307 µs80 µs10.7 µs
tuples4.35 ms264 µs237 µs277 µs83 µs64 µs
  • With Python values in, jlens is the fastest on fourteen of the seventeen cases: by 5.6 times on number formatting, 3.8 times on distinct items, 3.2 times on tuples, 2.5 times on recursion, 690 times on the index held in a variable, which jsonatapy and jsonata2py test against every item, and by 1.1 to 1.8 times on the rest. It is level with both on path (0.5 µs), and jsonata2py is ahead on names over items (13.2 against 13.7 µs) and the index into 10,000 items (0.7 against 0.8 µs).
  • With the input converted once, jlens is the fastest on fifteen of the seventeen cases, by 7.0 times on number formatting and 38 times on distinct items; jsonatapy is faster on path (0.2 against 0.4 µs, printed to a tenth) and on the index into 10,000 items (0.4 against 0.5 µs).
  • jsonata2py reads the Python values it is given, with nothing to convert, as compiled Python. Besides path and the two cases where it leads, it takes 1.3 to 7.1 times what jlens evaluate takes, and 1,400 times on the index in a variable.
  • jsonata-python takes 18 to 226 times what jlens evaluate takes on every case but path and the two indexes, and reads the whole input before evaluating: 1.1 ms on path and 20 ms on the index into 10,000 items.

jsonata-rs 0.1.4, a port of jsonata-java in Rust, left the tables after 0.27.0: it was slower than jlens on every case, and crashed the interpreter on deep and cyclic input. jsonata, which runs jsonata-js in the Duktape interpreter, is left out: no release since 2023, and its module cannot load jsonata-js on Windows.

Limits in Python

How each behaves at the limits, measured by python.py limits for 0.27.0 under Linux, with the packages of the table above; jsonatapy 2.2.17 gave the same answers for 0.37.0. Each case runs in a process of its own, killed after 30 seconds. $string($) reads the whole input, and the cyclic input is {"n": 1, "child": {"parent": <the input>}}:

Casejsonata-pythonjsonatapyjsonata2pyjlens
Input nested 900 levels, $string($)resultresultU1001result
Input nested 2,000 levelsresultresultU1001U1001
Input nested 100,000 levelsRecursionErrorresultU1001U1001
Cyclic input, nRecursionError111
Cyclic input, $string($)RecursionErrorruns onU1001U1004
Unbounded recursion, 1 + $f($n + 1)RecursionErrorU1001U1001D1011
The same, with a depth limit of 500D1011D1011no such optionD1011
Endless tail call, $f($n + 1)runs onruns onU1001 after 0.09 sruns on
The same, with a timeout of 1 sD1012 after 1.0 sD1012 after 1.0 sU1001 after 0.09 sD1012 after 1.0 s
  • jlens fails with a JSONata error in each case, and never ends the process. It refuses input nested more than 1,000 levels, which the others but jsonata2py accept as long as their stack or Python’s recursion limit lasts: a fixed limit that fails the same way on every platform, at the cost of inputs between 1,000 levels and that point.
  • jlens, jsonatapy and jsonata2py meet a cycle only when the expression reaches it; jsonata-python reads the whole input first, so n fails too.
  • jsonata2py stops each case with U1001, “stack overflow”, within 0.1 s. Its limits are low: probed on Windows, it accepts input nested up to 495 levels, a recursion such as 1 + $f($n + 1) up to 99 calls deep, and loops of 100,000 tail calls but not of 1,000,000.
  • No package stops an endless evaluation by default: set a timeout.

Java against the other implementations

cargo xtask java-compare compares the Java package with two other JSONata implementations for the JVM on Maven Central: jsonata-java, a port of jsonata-js to Java objects, and jsonata-jvm-compiler, which translates an expression to Java and compiles it with javac at run time, over Jackson trees. benches/compare/README.md says how to run it, and which packages it leaves out and why. jsonata-java gives jlens’s result on every case, jsonata-jvm-compiler on all but two: on tuples it gives arrays of the products where jsonata-js gives their sums, and on regex over a long text 4,150, as its \w is Python’s.

Measured for 0.37.0, on OpenJDK 25.0.5.1 (8 hardware threads), every engine in one JVM with -Xmx4g; jsonata-jvm-compiler for 0.34.0, as its version has not changed since. Each time is the best of five runs of 0.3 s after a second of warm-up, in the faster of two JVMs, as jsonata-java ran filter + aggregate 30% slower in one of them. Each engine returns its own objects, not serialized: jlens maps, lists and boxed values. With the input converted once: Java maps for jsonata-java and evaluate(Object), a Jackson tree for jsonata-jvm-compiler, and a Document for evaluate(Document):

Casejsonata-java 0.9.11jsonata-jvm-compiler 1.0.7jlens evaluate(Object)jlens evaluate(Document)
path8.3 µs0.03 µs0.89 µs0.21 µs
names over items16.0 µs1.3 µs16.3 µs1.8 µs
filter + aggregate59 µs4.1 µs51 µs16.8 µs
group-by121 µs13.1 µs77 µs38 µs
sort + map443 µs37 µs169 µs130 µs
strings69 µs7.4 µs70 µs27 µs
regex95 µs11.9 µs64 µs43 µs
number formatting92 µs8.5 µs15.5 µs9.7 µs
object constructor104 µs6.9 µs95 µs58 µs
transform236 µs27 µs211 µs126 µs
recursion775 µs44 µs245 µs231 µs
shipping rule161 µs15.2 µs127 µs41 µs
index into 10,000 items151 µs0.04 µs1.2 µs0.36 µs
index in a variable660 µs6.8 µs1.3 µs0.46 µs
regex over a long text99 µsdiffers116 µs88 µs
distinct items22 µs18.2 µs94 µs10.7 µs
tuples151 µsdiffers95 µs64 µs
  • jsonata-jvm-compiler is the fastest on every case it agrees on but the index in a variable and distinct items, by 1.1 (number formatting) to 8.4 times (object constructor) against a jlens Document on the cases that take a microsecond or more, 5.2 times on recursion: its expression is a Java class, which the JIT compiles with the application.
  • Against jsonata-java, the other interpreter, jlens over a Document is faster on every case. It takes less than a third of the time on recursion, sort + map and the shipping rule, and less than a ninth on number formatting.
  • Over Java maps, jlens takes 1.3 to 3.1 times as long as over a Document on the cases that read the order’s items, and 9 times on names over items and distinct items: each value read is a call back into Java, though a map is written with only the fields the expression reads (ADR 0021, amended). jsonata-java is then faster on distinct items, which reads whole items, and level on names over items and strings.

From JSON text, parsed at each evaluation, by its own parser for jsonata-java, by Jackson for jsonata-jvm-compiler, and by evaluateFromJson for jlens, which skips the fields the expression does not read:

Casejsonata-java 0.9.11jsonata-jvm-compiler 1.0.7jlens evaluateFromJson
path93 µs70 µs31 µs
names over items101 µs72 µs41 µs
filter + aggregate144 µs75 µs64 µs
group-by212 µs86 µs85 µs
sort + map526 µs109 µs175 µs
strings154 µs80 µs80 µs
regex182 µs84 µs85 µs
number formatting168 µs82 µs53 µs
object constructor189 µs80 µs107 µs
transform318 µs98 µs183 µs
recursion1.10 ms116 µs270 µs
shipping rule251 µs88 µs100 µs
index into 10,000 items1.45 ms1.38 ms882 µs
index in a variable1.98 ms1.33 ms882 µs
regex over a long text118 µsdiffers117 µs
distinct items108 µs93 µs69 µs
tuples240 µsdiffers110 µs

jlens is the fastest where the parsing is the cost (path, names over items, filter + aggregate, number formatting, distinct items and the two index cases), and level with jsonata-jvm-compiler on group-by, strings and regex; jsonata-jvm-compiler where the evaluation is, 116 against 270 µs on recursion. jlens is faster than jsonata-java on every case but regex over a long text, where they are level.

On the documents of ADR 0021’s spike, 1,000 and 100,000 items of five fields each, an index or $count takes the same time at both sizes in jlens, 0.3 to 0.5 µs against a Document, where jsonata-java takes 57 µs and 7.1 ms for items[0].name. From JSON text, jlens takes about half the time of the others on 100,000 items, but on $, for which it builds the whole document as Java objects.

Evaluations per second of $sum(items.price) on the JSON text of 100 items (9.5 KB), on 1 to 8 platform threads (four of the M1’s eight cores are efficiency cores) and on 1,000 virtual threads, each engine parsing the text at each evaluation; jsonata-java, whose compiled expressions are not thread-safe, compiles one per thread:

Engine1 thread2 threads4 threads8 threads1,000 virtual threads
jlens, JSON text43,424 (1.0×)84,689 (2.0×)162,618 (3.7×)212,267 (4.9×)212,733 (4.9×)
jlens, Java objects parsed by Jackson17,062 (1.0×)33,506 (2.0×)63,887 (3.7×)84,426 (4.9×)85,024 (5.0×)
jsonata-java 0.9.1118,694 (1.0×)36,454 (2.0×)69,624 (3.7×)92,833 (5.0×)93,285 (5.0×)
jsonata-jvm-compiler 1.0.719,501 (1.0×)38,177 (2.0×)73,603 (3.8×)99,066 (5.1×)99,066 (5.1×)

jlens leads at every count of threads, by 2.1 times or more. Parsed by Jackson into Java maps first, the parse, not the evaluation, is the cost.

Limits on the JVM

Measured by cargo xtask java-compare limits under Linux on the Ryzen, with the cases of python.py limits; jsonata-java 0.9.11 gave the same answers as 0.9.10 for 0.36.0. Each case runs in a JVM of its own, on its main thread with the default stack, killed after 30 seconds. jlens reads Java objects (evaluate(Object)), jsonata-java maps, and jsonata-jvm-compiler a Jackson tree, built the same way, since text cannot hold a cycle:

Casejsonata-java 0.9.11jsonata-jvm-compiler 1.0.7jlens
Input nested 900 levels, $string($)resultresultresult
Input nested 2,000 levelsresultresultU1001
Input nested 100,000 levelsStackOverflowErrorStackOverflowErrorU1001
Cyclic input, nStackOverflowError11
Cyclic input, $string($)StackOverflowErrorStackOverflowErrorU1004
Unbounded recursion, 1 + $f($n + 1)StackOverflowErrorU1001D1011
The same, with a depth limit of 500JException (stack overflow, depth 501)no such optionD1011
Endless tail call, $f($n + 1)runs onU1001 after 0.6 sruns on
The same, with a timeout of 1 sJException (timeout) after 1.0 sU1001 after 0.6 sD1012 after 1.2 s
  • jlens fails with a JSONata error code in each case but the endless loop with no timeout. No JVM crashed: a StackOverflowError is thrown to the caller, who must catch an Error rather than an exception to survive it, and it can leave an application’s own state half updated.
  • jsonata-jvm-compiler turns a stack overflow into U1001. It has no tail calls, so the endless tail call stops there too, and so would a loop of 100,000 tail calls. It has no depth limit.
  • jsonata-java takes a depth limit and a timeout (Frame.setRuntimeBounds), and reports them with messages, not codes.

The regular expression engine

jlens-regress, jlens’s fork of regress (ADR 0020), has a benchmark of its own, crates/jlens-regress/benches/engine.rs, whose cases are in engine.json beside it. Each case finds every match of a pattern in a text, as jlens does: from the end of the previous match, without an interrupt, or with one (when the evaluation has a timeout or a cancellation token). The texts are 200 lines of a log (15 KB), a sentence of English repeated to 12 KB, and a sentence of Portuguese, Greek and Japanese repeated to 20 KB of UTF-8. engine.mjs runs the same cases in Node.js, with exec and the flag g, as jsonata-js does.

Each variant is a binary of its own, built with functions and blocks aligned, in a target directory of its own, since two copies of the backtracker in one binary are inlined differently:

export RUSTFLAGS="-C llvm-args=-align-all-functions=6 -C llvm-args=-align-all-nofallthru-blocks=5"
export CARGO_TARGET_DIR=target/aligned
cargo bench -p jlens-regress --bench engine            # without an interrupt
JLENS_REGRESS_INTERRUPT=1 cargo bench -p jlens-regress --bench engine
node crates/jlens-regress/benches/engine.mjs           # V8

Each run saves its times and prints what the check costs against the last run of the other variant. A change to the engine is measured the same way, aligned, against the revision before. Measured for 0.37.0 (the median of 31 samples of at least 5 ms, and of three runs without an interrupt and two with one; V8 13.6, Node.js 24.22):

CasePatternMatchesjlens-regressWith an interruptV8
literalstatus=2002005.3 µs5.2 µs (−1.9%)11.2 µs
literal, no matchstatus=5000505 ns508 ns (+0.6%)7.2 µs
case-insensitive literallazy dog, i2006.1 µs6.5 µs (+6.6%)10.0 µs
classes\d{4}-\d{2}-\d{2}T[\d:]+Z20028.2 µs28.5 µs (+1.1%)15.8 µs
classes, no match\d{3}-\d{4}03.5 µs3.5 µs (+0.0%)1.6 µs
alternation of words\b(?:fox|dog|cat)s?\b400136 µs139 µs (+2.5%)15.3 µs
words\b\w+\b2,400175 µs180 µs (+2.9%)77.0 µs
capturesuser=(\w+) id=(\d+)20027.4 µs27.9 µs (+1.8%)11.5 µs
lazypath=(.*?) 20036.2 µs36.4 µs (+0.6%)9.2 µs
lines^.*status=200$, m20028.9 µs29.4 µs (+1.7%)15.1 µs
backreference, no match(\w+)\s+\10485 µs500 µs (+3.1%)150 µs
lookahead\w+(?=,)200410 µs425 µs (+3.7%)139 µs
lookbehind(?<=the )\w+200150 µs165 µs (+9.8%)51.9 µs
Unicode text\S+2,000151 µs156 µs (+3.2%)68.8 µs
Unicode text, case-insensitiveγράμματα, i20022.3 µs22.4 µs (+0.4%)7.4 µs
Unicode property\p{L}+, u2,000210 µs215 µs (+2.5%)331 µs
anchored, short text^1[0-9]$ on 17141 ns45 ns (+9.8%)37 ns
CompilationPatternjlens-regressV8 new RegExpV8, and a first exec
date-time^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$6.5 µs1.6 µs14.9 µs
e-mail, case-insensitive^[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,}$, i7.4 µs1.1 µs24.9 µs
Unicode property\p{L}+, u3.2 µs24.5 µs55.0 µs
  • V8 compiles a pattern to machine code, and is 1.8 to 9 times faster wherever the engine runs its instructions at many positions of the text: alternations, classes, lookarounds, backreferences. jlens-regress is a backtracker that interprets its instructions. It is faster where it can search for a literal first (memchr): 2.1 times on literal, 14 times on a literal that does not occur; and on \p{L}+.
  • jlens compiles a regex literal once per compiled expression, the first time an evaluation reaches it, and every later evaluation, on any thread, uses that pattern (since 0.37; before, each evaluation compiled it again). V8’s new RegExp only parses the pattern; the first exec compiles it.
  • The interrupt costs about 2.8% over these 17 cases (the geometric mean), from 1.9% faster to 9.8% slower per case (lookbehind and anchored, short text, 10% in each run), most of that spread from how the compiler allocates the backtracker’s registers, not from the check itself.

Through jlens, $match, $replace, $split and $contains are linear in the text since 0.27, and with a regex literal they build only what their result holds: on 20 KB of text with 1,558 matches of /\w+/, $replace takes 0.23 ms against 0.48 ms in jsonata-js, and $match, which returns an object for each match, 0.81 ms against 0.36 ms (measured for 0.28 against a Document, on the Ryzen). Since 0.31, three allocations of each match are left, those of its object; with mimalloc, $match took 0.38 ms, so the gap left is the Windows heap.

What the limits cost

Every evaluation counts its steps for the step limit (ADR 0018). Without a limit the budget is too large to be spent, so a step costs the same comparison with or without one. The timeout reads the clock at every 256th step rather than at every step, so a timeout fires at most 256 steps late. On a loop of 300,000 small steps, a timeout that never expires costs 0.3% natively and 2.4% in WebAssembly, where the clock is a call out of the module, and a step limit that is never reached at most 1.1% (measured for 0.20). A regular expression under a timeout or a cancellation token checks it every 1,024 steps of the backtracker (ADR 0009), the engine’s interrupt.

Using the API efficiently

  • Compile once. Expression::compile (new Expression in JavaScript) parses and post-processes. A compiled expression is immutable: keep it, share it between threads (it is Send + Sync), and evaluate it as often as needed.
  • Reuse documents. evaluate converts the parts of the input that the expression reads. For an expression that reads all of a 24 KB document, that costs about 40 µs natively, and about 160 µs in WebAssembly. To evaluate several expressions against one document, such as a set of rules, or one expression repeatedly, convert the document once.
  • Prefer JSON text when you have it. Document::parse (evaluateJson in JavaScript) parses straight into jlens’s representation. That is faster than parsing into a serde_json::Value and converting it.
  • Audit at the level you need. Without a tracer, auditing costs nothing measurable; see ADR 0004. Level decisions records only what explains a result. full records every node, with its input, and is for debugging.

Reusing documents

#![allow(unused)]
fn main() {
use jlens_core::{Bindings, Document, Expression, Options};

let doc = Document::parse(r#"{"items": [{"price": 2}, {"price": 3}]}"#)?;
let rules: Vec<Expression> = ["$sum(items.price) > 4", "$count(items) < 10"]
    .iter()
    .map(|source| Expression::compile(source))
    .collect::<Result<_, _>>()?;
for rule in &rules {
    let outcome = rule.evaluate_document(&doc, &Bindings::new(), &Options::default())?;
}
Ok::<(), Box<dyn std::error::Error>>(())
}
const doc = new Document(input);              // or Document.fromJson(text)
for (const rule of rules) rule.evaluateDocument(doc);
doc.free();

Evaluations never modify a document, so one document serves any number of evaluations. A Document is not Send. Convert it on the thread that uses it.

Document::parse_cut parses JSON text without the fields that the rules do not read, given what they read (ADR 0016): one rule’s Reads::input, or the union of the rules’. It checks the syntax of the fields it skips but does not convert them, so the narrower the reads, the faster the parse:

ParseDocument::parseDocument::parse_cut
The 24 KB document, cut by what names over items reads65 µs37 µs
The same, cut by the union of every case (the transform reads it whole)65 µs65 µs
1,000 records of 40 fields (1 MB), cut by what $sum(records[status = 'open'].amount) reads3.18 ms1.19 ms

A rule that reads a document whole leaves nothing to skip, and then parse_cut costs what parse does.

The WebAssembly and Python packages parse this way: Document.fromJson and Document.from_json take a Read, and evaluateJson and evaluate_json cut their input by what the expression reads. On the Ryzen, in Python, 1,000 records of 40 fields (790 KB) parse in 5.5 ms whole and 1.6 ms cut by the rule above, and evaluate_json evaluates it on them in 1.6 ms in all; in Node.js, evaluateJson evaluates the rule on 1,000 such records (1.4 MB) in 5.7 ms.

jlens eval parses its input this way too, by what the expression reads. Measured end to end on the Ryzen, process start included, before and after:

jlens evalParsed wholeParsed cut
$sum(items.price) on 30,000 items of 5 fields (10 MB)76 ms27 ms
$count(items) on the same73 ms21 ms
--ndjson --filter '$sum(items.price) > 470' on 20,000 lines of 5 items (34 MB)175 ms95 ms
$length($string($)) on the 10 MB document, which reads it whole159 ms107 ms

The last row gains too: the input used to be parsed into a serde_json::Value and converted, where it is now parsed straight into a Document.

Documents built from Rust values

An application that keeps its state in Rust types builds its document with Document::from_serialize, which serializes the state straight into it (ADR 0019), rather than through a serde_json::Value. The benchmark host_state (cargo bench -p jlens-core --bench host_state) measures a state of ten records of twenty fields (strings, numbers, booleans, small lists), rebuilt at each iteration:

host build: building the documentTime
serde_json::to_value alone, for reference9.3 µs
to_value + Document::new19.4 µs
serde_json::to_string + Document::parse18.6 µs
Document::from_serialize9.3 µs

host rebuild builds the document and evaluates the first 1, 4 or 10 of ten small expressions (filters, sorts, [0]) against it, as an application does between two changes of its state. For comparison, the last two rows build no document: lazy evaluate over the serde_json::Value, and evaluate_source over a Source written over the state, which reads only the fields each expression reaches:

host rebuild1410
to_value + Document::new + evaluate_document20.1 µs23.4 µs32.2 µs
Document::from_serialize + evaluate_document10.2 µs13.4 µs22.1 µs
to_value + evaluate10.9 µs16.7 µs29.9 µs
evaluate_source1.6 µs7.5 µs22.2 µs

For up to four evaluations per state, a Source is the fastest; at ten, a document built with from_serialize is level with it.

host binding reads one of the ten records through a variable ($self.score > 50 and $self.active). A variable of Bindings is a serde_json::Value, of which each evaluation converts what the expression reads; evaluate_document_with binds the record’s part of the document (Document::pointer("/items/3")), which is not converted:

host bindingTime
$self from Bindings0.31 µs
$self bound to doc.pointer("/items/3")0.15 µs
items[3] read from the document, for reference0.30 µs

Variables against a Document

An evaluation against a Document cannot read a variable lazily, as evaluate_with does: a lazy value borrows the Bindings, and a document’s values are 'static (ADR 0019). Since 0.27 it converts what reads() says the expression reads of each variable, analysed once for each expression; before, it converted each variable whole.

A variable of 1,000 records of seven fields, about 130 KB, against a document of one field, on the Ryzen, with functions and blocks aligned, in µs, the fastest of 15 rounds of one process:

ExpressionBefore 0.270.27evaluate_with
$v.total1,0500.640.57
$v.owner.name1,0500.990.92
$v.items[3].price1,0502331.77
$sum($v.items.price)1,09026087
a + 1, the variable not read1,0500.210.59
$count($keys($v)), read whole1,0501,0582.2
$self.hp > 10, five fields1.550.680.52
a > 10, five fields not read1.510.210.49
$x + a, a number0.3150.3280.41
a + 1, no variables0.1990.2020.30

What is still slower than a lazy read is an array read for a few of its items: $v.items[3].price converts price of all 1,000 items. A variable read whole costs what it did. To read a large variable for a few of its parts, bind a part of a Document instead (evaluate_document_with and Document::pointer, above), which converts nothing. The Python and Java packages evaluate this way too: from Java, $v.total takes 0.83 µs where it took 630. From 0.35 the Java package binds a Document to a variable as well (evaluate(input, Map.of("table", document))): on the M1, $table.items[0].name over 100,000 items takes 0.8 µs, and 8.3 ms with the variable in Bindings.

Where the time goes

  • Allocation. Values are reference-counted (Rc). Objects keep their fields in insertion order, in a vector searched in order; one of more than 8 fields also keeps an index of its keys (ADR 0022). Their keys are shared strings: converting a document allocates each distinct key once, not once per object. Building results, sequences and tuple streams allocates, and that is most of the cost of evaluation.
  • Sequences. Following jsonata-js, paths build sequences step by step and flatten them. Predicates evaluate per item, in a fresh frame. A step that reads an array passes it on as it is, and a step whose results hold no array to flatten makes them its sequence without copying.
  • Shortcuts for common shapes. Without a tracer, evaluation skips work that no result depends on. A path of names on a single object (customer.name, $i.code) looks its fields up instead of building sequences; a name mapped over the items of a path is looked up in each item; a predicate built from literals and variables ([[0..19]], [$i]) is evaluated once and picks its items; an object constructor over one item evaluates its pairs without grouping; = with a string literal compares with the literal’s text. With a tracer, evaluation takes the general path, so audits report every node; a property test checks that both paths agree.
  • Converting the input. evaluate converts the parts of the input that the expression reads, as it reads them (ADR 0010): a path step reads only the field it looks up, and an index only the items it picks. Through a Source, as the Python and Java packages read their values, each array or object read costs one allocation, and freeing it as much again. An expression that reads whole items pays for converting them.
  • Fixed cost. An evaluation reads the clock only when it needs it ($now, $millis, the seed of $random, a timeout), so customer.name against a Document takes 0.10 µs natively. From Python a call adds about 0.25 µs (its arguments, the interpreter released during the evaluation, the result built); from Java the C API and the call add about 0.12 µs, and the Ryzen’s 16 threads on one Document made 20.8 million evaluations of customer.name per second.
  • Calls of lambdas. A call of a lambda takes its frame and its arguments’ list from those that a call before it gave back, and allocates them only when none is free or something still holds them, a closure for one; a name of up to 14 bytes stays in the frame’s entry. A variable read in a lambda’s body knows which parameter holds it. Host functions are looked up on a miss, so that binding sixteen of them costs nothing per evaluation (ADR 0006).
  • Deep copies. A transform (|...|) copies its input with $clone before changing it, as jsonata-js does; jlens copies the value itself, with the values a copy through JSON text would give, where jsonata-js writes and parses the text. On the benchmark’s transform the copy takes about a fifth of the time; most of the rest is building the result.
  • Long inputs. $distinct keeps its first 16 distinct items by comparing, and looks the rest up by a hash, of the first values comparing reads when they tell the items apart, following them into the level below a field the items share: on the Ryzen, 100,000 strings take 15 ms, where jsonata-js, quadratic, takes 32 s. & in a loop holds its two sides and makes its text once, as V8’s ropes do. $substring walks the text only as far as its result. What cargo xtask growth still finds quadratic is so in any engine, as each step copies what it has built: $reduce that builds an array with $append or an object with $merge, and in over a long list for each item. An expression that does this over large input can be bounded with max_steps or max_array_length.
  • Link-time optimization. Every release build uses LTO, the C API and the WebAssembly module since 0.27 (2 to 24% faster). Its larger frames make a deep recursion overflow V8’s stack 4 to 9% sooner; the default maxDepth of 500 keeps a third of headroom (WebAssembly guide).

0.37 against 0.36.0

Measured for the release (roadmap 0.37 #16) on the M1, against builds of 0.36.0 made the same way, each run on a new copy of its build; the full comparison is in docs/notes/perf-0.37.md. 0.37 compiles a regex literal once per compiled expression, checks the size limits while a result is built, and finds a Java thread’s conversion of a document by its handle.

regex takes 11 to 15% less natively, 10 to 15% less in Python, 7 to 14% less in Java and 8 to 18% less in WebAssembly. $toMillis of an ISO 8601 timestamp, with no picture, takes 88% less (200 calls in 0.22 ms, 1.9 ms in 0.36.0), as its pattern is compiled once for the process. path against a Document takes 6% less natively and 7% less in Java. Natively every other case is within 3% in each mode. Python and Java slow no case past their marks (3.5% and 5%); Java’s one mark, filter + aggregate over Java objects, 9% slower in one comparison, is a draw of the JIT, as the table’s run of the same build gives 0.36.0’s time. In WebAssembly, regex over a long text takes 4% more (177 to 184 µs), in two steps of about 2% that native builds do not show: the size limits checked as $replace builds its text (#5), and the commits ported to jlens-regress (#20). Every other case is within 2.1%, but times under 4 µs, printed to a tenth.

Compiling customer.name reads 0.64 µs where 0.36.0’s table read 0.59 µs; built and run one after the other, 0.36.0 takes 0.61 µs and 0.37 0.60 µs, so the difference is between builds, not in the code. On its own benchmark, the engine is within 2% of 0.36.0 on every case but two faster (Unicode text 3%, anchored, short text 5%), and the interrupt costs 2.8% where it cost 2.4%.

Decision records

Architecture decision records (ADRs) capture significant design choices: the context, the decision, and its consequences. They are numbered and never rewritten. A later ADR supersedes an earlier one instead.

#DecisionStatus
0001Implement JSONata ourselves, porting jsonata-js 2.2.2Accepted
0002Use regress for ECMAScript-compatible regular expressionsAccepted
0003An explicit value model with Undefined and sequence flagsAccepted
0004Audit evaluations through a tracer interface in the evaluatorAccepted
0005Carry audit labels in JSONata doc-commentsAccepted
0006Host functions with a JSON boundaryAccepted; extended by 0011; amended to look host functions up on a miss
0007A language server on the language service, configured by jlens.jsonAccepted
0008A machine contract for the CLI: --json envelopes, exit codes, stdout for dataAccepted
0009Regular expressions stop within the evaluation’s limits, through a fork of regressAccepted; the fork made permanent by 0020
0010Input documents converted lazily, one level at a timeAccepted
0011Host functions call the functions they receive, through a handle that borrows the callAccepted
0012The CLI on npm: a launcher package and one package per platformAccepted
0013The VS Code extension: one package per platform with the release binaryAccepted
0014The Python package: PyO3 bindings that mirror the WebAssembly packageAccepted
0016The fields an expression reads: an abstract evaluation that gives an upper bound, and its unionAccepted
0017Results written straight into another representation, through a builder the core walksAccepted
0018A deterministic step limit: each evaluated node and callback is a step, fast paths charge what they skip, U1006Accepted
0019Documents serialized straight from Rust values, as serde_json::to_value and Document::new would build themAccepted
0020jlens-regress is jlens’s own fork of regress: upstream fixes ported, not rebasedAccepted
0021The Java package: a C API called through Panama, for Java 25Accepted; amended to ship before the API work, on what the Sink allocates, and to write maps with what the expression reads (0.26)
0022Objects keep their fields in a vector, with an index past 8 fieldsAccepted
0023The schema and the language service through the C API and in the Java package: a schema and a service by handle, diagnostics as JSON text; no completion, hover or signature helpAccepted
0024A recursive schema keeps its $refs as references by name to definitions of the schema, followed where the shapes are read; other $refs are copied in place as beforeAccepted; amended by 0025: a target copied too often is kept as a definition too
0025A $ref to another document: jlens never fetches, the application gives the documents by URI; a $ref that cannot be followed leaves its place unknown and is reported; a load bounded by the size of its documentsAccepted
0026jlens-schema reads JSON Schema itself, into shapes, and infers its own: validators answer questions about a document, not about a place; referencing weighed for $ref and kept apartAccepted

0001 — Implement JSONata ourselves, porting jsonata-js 2.2.2

Status: Accepted

Context

The project began as a rule engine built on a home-grown JSON DSL over JSONPath. It had all/any/not groups, vars, aggregate formulas such as sumProduct and avgField, and an audit tree. Each new requirement added more operators to that DSL, and it was drifting towards an under-specified programming language. JSONata already offers everything that DSL needed, and more:

  • path navigation and filters;
  • aggregation;
  • variables;
  • conditionals and result construction.

JSONata also has a specification and a language-neutral conformance suite.

We considered two options:

  1. Build on an existing Rust JSONata crate. That is less work up front. However, the existing crates cover the language only partially. They don’t expose an AST with stable spans or a recovering parser, and we would depend on a third party for the parts we need to extend most: auditing and tooling.
  2. Write our own implementation as a port of the reference implementation, jsonata-js 2.2.2.

Decision

We write our own implementation and port the reference implementation stage by stage: tokenizer, Pratt parser, processAST, evaluator, function library, date/time formatting and signatures.

The Java port (jsonata-java) and its annotated walkthrough serve as a secondary reference, especially for the pitfalls they document.

Correctness is measured against the official test suite (see Conformance testing).

Consequences

  • We control the AST, which lets us add precise spans, a recovering parser, trivia and comment annotations, and evaluator instrumentation for audits.
  • The cost is substantial: roughly 7,700 lines of JavaScript to port, including the date/time picture-string engine.
  • Conformance is objective and tracked per case, so behaviour differences are visible and must be justified in tests/conformance/overrides.json.
  • We track upstream JSONata releases by re-vendoring the suite (cargo xtask update-suite).

0002 — Use regress for ECMAScript-compatible regular expressions

Status: Accepted

Context

JSONata regex literals (/ab+c/i) and the functions $match, $replace, $split and $contains follow JavaScript regular-expression semantics. The suite relies on features such as backreferences, lookahead and lookbehind, and on JavaScript’s capture-group behaviour.

The regex crate deliberately omits backreferences and lookaround, because it guarantees linear-time matching. fancy-regex adds them, but its syntax and semantics are Perl/PCRE-like rather than ECMAScript.

Decision

Use regress. It implements ECMAScript regular-expression syntax and semantics in pure Rust, and it compiles to wasm32-unknown-unknown.

Consequences

  • We get regex behaviour that matches jsonata-js closely, including in the browser build.
  • regress is a backtracking engine, so a pathological pattern can take exponential time. The evaluation timeout guards against this (see Options::timeout), and the guides will warn about untrusted patterns. (It did not: a match ran as one evaluation step. ADR 0009 makes the timeout reach inside a match.)
  • Positions reported by $match must be converted from UTF-8 byte offsets to the UTF-16 code unit indices that JavaScript reports. That conversion is covered by dedicated tests.

0003 — An explicit value model with Undefined and sequence flags

Status: Accepted

Context

JSONata semantics depend on distinctions that plain JSON values cannot express:

  • undefined vs null. A missing path yields undefined, which disappears from arrays and objects. JSON null is a real value.
  • Sequences vs arrays. Path results are sequences. An empty sequence is undefined, and a singleton sequence collapses to its only item. Arrays that come from the input, or that an explicit [...] constructor builds, are never collapsed. The [] modifier (keepArray) and the wrapper that makes an input array count as a single context value add more cases.
  • Callables. Lambdas, native functions and regexes are first-class values.

The Java port encodes these as a null for undefined, a NULL_VALUE sentinel for JSON null, and an ArrayList subclass that carries flags. Its documentation names this the most error-prone part of the port.

Decision

The evaluator works on its own Value type:

#![allow(unused)]
fn main() {
enum Value {
    Undefined, Null, Bool(bool), Number(f64), String(Rc<str>),
    Array(Rc<Array>),            // Array carries: sequence | keep_singleton | outer_wrapper | cons | tuple_stream
    Object(Rc<IndexMap<..>>),    // insertion order is observable in JSONata
    Lambda(..), Native(..), Regex(..), Range(..),
}
}
  • Numbers are f64, as in JavaScript. Number-to-text conversion uses ryu-js so it matches JavaScript exactly.
  • Undefined never crosses the public API: results are Option<serde_json::Value>.
  • Values are reference-counted (Rc) for the lifetime of a single evaluation. The compiled AST is immutable and Send + Sync, so a compiled Expression can be shared between threads, and each thread evaluates with its own values.

Consequences

  • Each JSONata rule about undefined and sequences maps to a variant or a flag, and each is covered by a dedicated test.
  • Input is converted once from serde_json::Value at the start of an evaluation. If profiling shows that this conversion dominates, a borrowed view of the input can be introduced later.

Amendment: a string can be two strings joined (0.27)

A string is a Text: a text, Rc<str>, or two strings that & joined and nothing has read yet, Rc<Joined>. & copied both sides at each call, so a loop that grows a string with it, such as $reduce(strs, function($a, $b){ $a & $b }, ''), took time growing with the square of the string: 64,000 short strings took 1.06 s, where jsonata-js, whose strings are V8’s ropes, took 99 ms. Appending in place was the other candidate. It needs the left side to be the only reference to its string, which a loop never has, since the lambda’s frame holds $a while its body reads it.

  • A result of & of 256 bytes or more holds both sides. Its text is made the first time something reads it, walking the nodes with a stack of its own, and the sides are then dropped, so that a loop that reads each string it grows does not keep every one of them.
  • A side shorter than 256 bytes goes into the short text next to it, (a & b) & c being a & (b & c), so that a loop of short pieces holds a node for each 256 bytes or so, not one for each piece. Without that, adding single bytes up to the limit of a string’s length would have held about 88 bytes of nodes for each byte.
  • Dropping the nodes keeps a stack of its own too, as a loop makes them as deep as its count.
  • Text is two words, like Rc<str>: its second kind sits where Rc<str>’s pointer cannot be null. Value stays three words. What reads a string pays one test of that kind; what takes it as a key of an object or as the text of a regex makes its text.

The compiler’s drop of a Value grew with the second kind, and stopped being inlined into the drop of a list of values, which made each item of a dropped array a call: $sum(items.quantity) against a Document took 10% longer under Linux. An array of scalars is now freed without a drop for each item, which took that away. An array of objects or strings still makes the call for each item: dropping them by hand cost the index into 10,000 items as much as it gained $distinct, so it was left (performance page, 0.27 #16).

0004 — Audit evaluations through a tracer interface in the evaluator

Status: Accepted

Context

The original rule-engine design produced an audit tree for every evaluation. It recorded what each condition checked, the actual and expected values, and whether the condition passed. jlens keeps the language pure JSONata, with no separate rules layer, but it must still explain why an expression produced its result. JSONata itself only returns the final value.

Options considered:

  1. Re-evaluate sub-expressions after the fact. This is simple, but it doubles the cost, and it cannot see the state inside the evaluation: per-item filter outcomes, short-circuits and bound variables.
  2. Rewrite the expression to emit diagnostics. This is brittle and changes semantics.
  3. Instrument the evaluator with a tracer that receives events as evaluation proceeds.

Decision

The evaluator is generic over a Tracer trait. The trait receives these events:

  • enter and exit per node;
  • predicate per filtered item;
  • branch, bind, call and short_circuit.

Two implementations exist:

  • NoopTracer is the default. All of its methods are empty and inlined, so tracing costs close to nothing when it is off. The budget is under 3%, checked by benchmarks.
  • AuditCollector builds a serializable AuditTree. It offers capture levels (Off, Decisions, Full) and capture limits: value size, items per sequence, depth and node count.

An Explanation is derived from the tree: which operands made an and fail, which items a filter rejected, and so on. It renders as text for the CLI or as JSON for user interfaces. Optional tracing integration and JSONL event export cover operational logging.

Measurement

The untraced hot path stays the same as before: when no tracer is attached, Evaluator::eval checks for one and calls the original code, while the traced variant is a separate, cold function. Interleaved A/B runs of a throughput example (since replaced by the criterion benchmarks in crates/jlens-core/benches) against the evaluator before tracing measured between −5.7% and +2.7% across five workloads, which is within the machine’s noise and inside the 3% budget.

Consequences

  • Auditing reuses the real evaluation, so what the audit shows is exactly what happened.
  • The evaluator code has to emit events consistently. This adds work that is comparable in size to the core evaluator, and the roadmap plans for it as its own phase.
  • Audit trees for large inputs are bounded by the capture limits, so audits stay usable in production.

0005 — Carry audit labels in JSONata doc-comments

Status: Accepted

Context

Business users need audit output in their own terms. They want to read “Authorized customer: failed”, not “binary in at 12..48 returned false”. The original DSL had label and message fields on every condition. JSONata has no syntax for metadata, and adding new syntax would make expressions unportable to other JSONata implementations.

Decision

Annotations are written as JSONata block comments that start with /**. Each annotation attaches to the sub-expression that immediately follows it:

/** @label "Authorized customer" @message "Login must be on the approved list" */
customer.login in $approved
  • The lexer keeps comments as trivia, with spans. The parser attaches a doc-comment to the next AST node it produces.
  • Recognised tags are @label, @message and @id. Tag values are JSON strings. Unknown tags produce a diagnostic warning, not an error.
  • Plain /* ... */ comments remain comments and carry no meaning.

Consequences

  • Annotated expressions are still valid JSONata, and every other implementation ignores the annotations.
  • Labels appear in the AuditTree, in explanations, and in editor hovers.
  • Annotation placement depends on the parse. The annotation documentation will specify precisely which node a comment attaches to, including for operators and for and/or chains.

0006 — Host functions with a JSON boundary

Status: Accepted; extended by ADR 0011, which lets host functions call the functions they receive. Amended in 0.25: host functions are looked up when no frame holds a name (below).

Context

jsonata-js lets applications pass their own functions in the bindings of an evaluation, or register them on an expression with registerFunction. Rule engines use this to reach data and services the document does not hold: rate tables, currency conversion, lookups. jlens had no equivalent, because Bindings held only JSON values.

A host function has to fit four constraints:

  • Expression is Send + Sync, and Bindings is too. Applications share both between threads.
  • The run-time Value (ADR 0003) is internal. It is built on Rc, so it is not Send. It also carries the sequence flags of jsonata-js, which a host should not have to know about.
  • Evaluations never mutate their input, and a Document is shared between evaluations.
  • Without a tracer, the evaluator must not get slower (ADR 0004).

Options considered for the values that cross the boundary:

  1. Expose Value, with accessors. This is the fastest option, with no conversion, and callbacks are possible. But it makes the internal model, its flags and its Rcs a public API.
  2. A new public value type. It needs a conversion anyway, and adds a third value model next to serde_json::Value and the internal one.
  3. serde_json::Value, with None for undefined. This is the type of documents, results and variable bindings already, and every Rust JSON tool works with it.

Decision

  • The boundary is JSON. A HostFunction wraps an Arc<dyn Fn(&[Option<JsonValue>], &HostCall) -> Result<Option<JsonValue>> + Send + Sync>. Arguments are converted with the same rules as results (JSON.stringify): a function argument arrives as None. The context value is converted only when the function asks for it (HostCall::input), since it can be the whole document.
  • Optional signatures reuse the parser and validator of the built-in functions. A validated call behaves like a call to a built-in: same type errors, same context substitution. A function without a signature declares its arity, which plays the part of a JavaScript function’s length for higher-order functions and partial application.
  • Bindings hold values and functions. A name holds one or the other: binding one replaces the other. Each evaluation binds the host functions in its root frame next to the variables. So they take precedence over built-in functions of the same name, as in jsonata-js. (Since 0.25 they are looked up when no frame holds a name, with the same precedence: see the amendment.)
  • Function values gain a Host variant. Partial application of built-in functions is generalized to host functions: Partial holds the target function.
  • Errors are jlens_core::Errors with a code chosen by the host. As for any error, the call site fills in the position and token when the error has none.

Consequences

  • Bindings and HostFunction are Send + Sync. In WebAssembly, JavaScript functions are not Send, so the bindings refer to them indirectly, through a registry local to the evaluation.
  • In WebAssembly, this is undefined, where jsonata-js passes the context value. Passing it would convert the context value to JavaScript at every call, which is the whole document for a call at the top of the expression. A signature with - passes it as an argument instead. An exception thrown by a JavaScript function is kept, and the evaluation rethrows it as is. A promise is refused (U1002), since evaluation is synchronous.
  • Each call copies its arguments and its result. For the functions that rule engines call, which take a few scalars, the cost is small. It is large only for a function that receives a large array or object.
  • A host function cannot call a JSONata function it receives as an argument. A later decision can add a callable handle, or a public value type, without changing the functions written against this API. ADR 0011 added that handle (HostCall::function) in 0.13.0.
  • The evaluator’s hot path only gains match arms. Tracing needs no new event: a host call is a function call node, with its enter and exit events.
  • Host functions run to completion. The evaluation’s timeout is checked again once they return.

Amendment: host functions looked up on a miss (0.25)

Context

Each evaluation bound every host function in its root frame before it started, a HostFunction cloned and its name allocated, called or not. The Java package measured it (ADR 0021, 0.25 #7): about 0.09 µs per function per evaluation, and in Rust $a + $b took 2.82 µs with sixteen functions bound against 0.39 µs with none. A rule engine that binds dozens of functions paid microseconds for each rule, in every package.

Decision

The root frame looks a name up among the bindings’ host functions when no frame holds it, before the built-ins, and keeps the value it finds, as it keeps a built-in’s. The precedence does not change: a variable, of the bindings or a document bound by evaluate_document_with, is in the root frame and found first; then the host functions; then the built-ins. A function bound by the expression or by a lambda’s parameter is in a nearer frame. The value kept makes $f = $f hold, wherever in the expression each $f is.

Consequences

  • An evaluation pays only for the host functions it names, once each. On the maintainer’s Windows machine, $a + $b takes 0.40 µs with one, four or sixteen functions bound, against 0.39 µs with none; $add(1, 2) with sixteen bound 0.75 µs instead of 3.11.
  • A name that no frame holds costs a lookup in the bindings’ functions before the built-ins, once per evaluation and name, since the value is kept.
  • Every lookup carries the bindings to the root frame, which a name found in a nearer frame never reaches, yet costs: cargo xtask ab against 0.24.0, built aligned, put recursion ($f(15), about 2,000 calls of a lambda) 2.5 to 5.6% slower in every mode, the other cases within 2% (0.25 #15). Inlining Frame::lookup and variable brings it to about 2% (between 1.2 and 2.6% over nine builds, by the fastest round); 0.24.0 rebuilt is within 1.1% of itself. The rest stays: keeping the functions in the root frame instead would tie the bindings to the lifetime of the values. (Undone in 0.26, below.)

Follow-up: the functions in the root frame (0.26 #2)

Built as an application builds it, without the alignment flags, the 0.25 code ran recursion 4.0% slower than 0.24.0 with evaluate and 2.9% against a Document. The root frame now holds the host functions itself: Bindings keeps them behind an Arc, which the root frame clones, and holds None when there are none. The lifetime of the values is not involved, since the frame owns its share of them. Frame::lookup and variable take no bindings again and are no longer marked #[inline], as in 0.24.0. The precedence and the value kept do not change. Since 0.26 #11, Bindings itself holds None until its first function, so that empty bindings, which a host may build at each call, allocate nothing (26 ns with mimalloc).

  • cargo xtask ab v0.24.0 . puts recursion within 1.1% in both modes, built aligned or not (evaluate +0.7% unaligned and +1.0% aligned, document +0.5% and +1.1%), and every other case within 2.3%. One unaligned run against a Document gave recursion +8.8%; two more runs of the same build gave +0.1% (the case alone) and +0.5%.
  • An evaluation with host functions pays one atomic increment and decrement of the Arc; $a + $b still takes 0.38 to 0.39 µs with none, one or sixteen bound, and $add(1, 2) with sixteen 0.72 µs, as before within 1%.
  • Cloning Bindings shares the functions’ map instead of copying it; adding or removing a function on a clone copies the map then, as cloning did before.

Follow-up: the variables of a frame (0.26 #18)

A call of a lambda makes a frame, and each frame held its variables in a hash table: a seed for its hasher, read through a thread-local, an allocation, control bytes to set and a hash per name, for one or two names. A frame now holds up to eight variables in a list and moves them to a table at the ninth, as the root frame does when a host binds many. recursion takes about 21% less time under Linux and 4.6% less on Windows, and the difference between two calls that 0.26 #17 could not explain is gone.

The cost falls on frames with many names: a block with eight or more takes 4 to 12% longer, 0.1 to 0.2 µs on twenty lookups, as searching eight names of one length costs more than hashing one, while up to four names take 7 to 8% less. Eight was kept for that: most frames hold far fewer.

Follow-up: a lambda’s frame (0.26 #20)

A frame of a call now holds the list that carried the arguments and a reference to the function, whose parameters name them, instead of a list of its own with a copy of each name. The function is an Rc of the evaluation, not the Arc<LambdaDef> of the syntax tree, as a count on the tree is one cache line for every thread. A name the body binds in that frame moves it to the list of names. Of two parameters of one name the last holds, as when they were bound in turn. A call makes two allocations instead of four, and takes no share of the tree: recursion takes 18 to 20% less time on Windows, 8 to 10% less under Linux, and 44% more evaluations on eight threads (performance notes).

The new reference from a frame to its function makes no new cycle that an evaluation would keep: the function reaches the frame’s parent, which the frame holds anyway, and its input, made before the frame. Any other way back goes through a frame’s variables, and a frame holding a function, an array or an object is on the list that is cleared when the evaluation ends.

Follow-up: names kept in place (0.27 #7)

The other frames kept a copy of each name, an allocation per binding. A name of up to 14 bytes now stays in the list’s entry, and a frame with one name holds it with no list, so that a block of one name makes no allocation for its frame’s variables. An Arc<str> in the syntax tree, the other candidate, was not built: it would count on one cache line for every thread at each binding, what 0.26 #20 took out. A name of 15 bytes or more takes one pointer, so one allocation more than before; the list a one-name frame no longer makes pays it back. The name is 16 bytes, not 24 as a Box<str> beside 22 bytes would take: at 24, a frame’s variables fill their type and recursion, which binds no name, took 3.5% more with mimalloc (performance notes).

0007 — A language server on the language service, configured by jlens.json

Status: Accepted

Context

The language service (jlens-schema) completes, checks and documents expressions against a schema. The browser reaches it through the WebAssembly package. Other editors (Neovim, Helix, Emacs, VS Code) speak the Language Server Protocol. They need a server, and a way to know which schema, variables and host functions apply to which files.

Choices to make:

  1. The protocol library. tower-lsp is asynchronous and brings tokio. lsp-server and lsp-types, the libraries of rust-analyzer, are synchronous: a loop over messages on channels, with few dependencies. The language service is synchronous and fast (it parses and types one expression), so nothing would run concurrently.
  2. The binary. A separate jlens-lsp executable, or a command of the existing CLI.
  3. The configuration. Settings per file, written in each expression (an annotation such as @schema), or one file per workspace that maps paths to settings.

Decision

  • lsp-server and lsp-types. The server is a loop over messages. It keeps the open documents and one language service per configuration entry, built on first use.
  • A library crate, jlens-lsp, run by jlens lsp. Installing the CLI installs the server; embedders can run the library on another connection, as the tests do in memory.
  • jlens.json at the root of each workspace folder. It maps glob patterns, relative to its folder, to settings: a schema file, variables with their schemas, and host function declarations. The first matching pattern applies. Expressions stay pure JSONata, and one file configures a whole folder of rules. The same object can come as initializationOptions.
  • Reloading. The server asks the client to watch **/*.json. Any change to a JSON file reloads the configuration and forgets the built services, so changed schemas are read again, and the open files are checked again. Saving a JSON file in the editor does the same, for clients that do not watch files.
  • Positions. UTF-8 when the client offers it, UTF-16 otherwise. Positions past the end of a line are clamped to it, and a position inside a character means its start.

Consequences

  • Every editor with an LSP client gets the features of the web editor, with no editor-specific code. Only VS Code needs an extension to start the server, which jlens does not publish yet.
  • Requests are answered one at a time, in order. That is enough while the service answers in well under a millisecond. Expensive features would need cancellation, or a worker thread.
  • Configuration lives outside the expressions, so the same expression can be checked against different schemas in different folders. The cost is a file to maintain next to the rules.
  • Reloading on any JSON change is coarse, but cheap: services are rebuilt lazily.

0008 — A machine contract for the CLI

Status: Accepted

Context

Scripts, CI jobs and coding agents run jlens and read what it prints. Today they parse output written for people:

  • jlens eval prints the result as JSON, but an undefined result prints nothing, which looks the same as a failure that printed nothing. Errors go to standard error as one line of text, with the position inside the message.
  • With --ndjson, failures are text on standard error, with a line number in the message; the results on standard output carry no line number at all, so a consumer cannot pair a result with its input line once a line has failed.
  • eval reads standard input when no -i is given. Started from a terminal by mistake, it waits forever, which an agent cannot tell from a slow evaluation.
  • Results of $now(), $millis(), $random() and $shuffle() change from run to run, so the same command cannot be replayed to check a result.

Choices to make:

  1. How output becomes machine-readable. Detect whether standard output is a terminal and switch format (as ls and git do), or add an explicit flag.
  2. The shape of a result. The bare value, as today, or a value wrapped in an object that also says whether the evaluation succeeded.
  3. Where errors go in machine mode: standard error, as today, or standard output next to the results.

Decision

--json: one envelope per evaluation

jlens eval --json prints one compact JSON object, the envelope, per evaluation, on one line of standard output:

OutcomeEnvelope
A result{"ok":true,"result":…}
An undefined result{"ok":true,"undefined":true}
An error{"ok":false,"error":{"code":…,"message":…,"position":…,"line":…,"column":…}}
  • undefined is a separate field because null is a valid result.
  • code is the JSONata error code (S0202, T2001, D1012, U1001…), the one stable thing to match on. message is for people and may change.
  • position is the JSONata position of the error, a UTF-16 offset into the expression, as in jsonata-js; it usually points just past the offending token. line and column are 1-based and point at the start of the offending text, with the column counted in characters, as the human report prints it. The three fields are absent when the error has no location.
  • With --ndjson, every envelope also carries "line", the number of its input line, so results and errors can be paired with their input. Blank lines are skipped and produce no envelope.
  • With --filter, a matching document is the result. Documents that do not match produce no envelope; errors still do.
  • An input document that is not valid JSON is reported in an envelope too, with code U2001.
  • --json implies --compact. It cannot be combined with --raw-output, --explain or --audit, which have their own output formats.
  • Fields are only ever added to the envelope, never renamed or removed. Consumers must ignore fields they do not know.

Exit codes

CodeMeaning
0Every evaluation succeeded
1The expression has errors: a syntax error, an evaluation error, or (with --ndjson) at least one line that failed
2Usage or I/O problem: bad arguments, an unreadable file, a single input document that is not valid JSON, a terminal on standard input

The codes are the same with and without --json; only the output format changes.

Standard output is data, standard error is for people

  • Standard output carries only data: results, envelopes, diagnostics with --json, catalogs.
  • Standard error carries text for people: rendered diagnostics, warnings, usage errors.
  • In --json mode the envelope is complete: an expression error is in the envelope on standard output, and nothing needs to be read from standard error.
  • Problems with exit code 2 are reported on standard error only, and standard output stays empty. They happen before any evaluation, and some of them (bad arguments) are detected before jlens knows which format was asked for. A single input document that is not valid JSON is the exception: in --json mode it is also reported as an envelope.

Never wait on a terminal

eval without -i or --no-input fails with exit code 2 when standard input is a terminal, instead of waiting for a document that will never come.

The default stays human

Without --json, output is unchanged: results printed like jq, diagnostics rendered with the source line and a caret. The format never depends on whether standard output is a terminal, so a command behaves the same when an agent runs it and when a person copies it into a shell.

  • jlens check --json prints one compact JSON array of diagnostics, each with file, line and column next to the code, message and byte span. --deny-warnings makes warnings fail with exit code 1.
  • jlens functions --json and jlens errors --json print their catalogs on standard output.
  • jlens eval --now and --seed fix the clock and the random generator, so that the same command, expression and input print the same bytes.

Consequences

  • Machine mode is one flag that a script or an agent passes on purpose. Nothing switches format behind its back, and the human output can keep improving without breaking anyone.
  • A consumer reads one line per evaluation, decides on ok, and matches errors by code. It never parses messages or standard error.
  • Envelopes cost a few bytes per result. Pipelines that want bare values, such as jlens eval --ndjson | jq, keep using the default output.
  • U2001 is a new code, for input rather than expressions. It joins the error catalog, and so the generated error reference.
  • The contract is public: changing it takes a new ADR, and the envelope only grows.

0009 — Regular expressions that stop within the evaluation’s limits

Status: Accepted; ADR 0020 makes the fork permanent, superseding the plan in decision 3 to go back to regress

Context

ADR 0002 chose regress, a backtracking engine, and counted on the evaluation timeout to stop pathological patterns. It does not. The evaluator checks the timeout and the cancellation token between evaluation steps (Evaluator::guardrails in eval.rs), and a match is a single step. Measured on 2026-10-11, in a debug build with jlens eval --no-input --timeout 100, $contains('aa…a!', /^(a+)+$/) with n a’s ran for 1.2 s at n = 20, 9.9 s at n = 23 and 80 s at n = 26. In WebAssembly the page freezes for that long. Untrusted expressions were the use case the 0.5 limits were built for, and a regex literal gets through them.

What regress offered when this was decided (0.10.5, the version in use, and 0.12.0, the latest):

  • No limit and no hook. Neither the public API nor the backtracker (classicalbacktrack.rs) has a step budget, a deadline, or a callback.
  • No linear-time backend. The optional backend-pikevm is not a Pike VM in the automata sense: it explores states depth-first on a stack, cloning each state, and never merges duplicates, so it is exponential on the same patterns. It also panics on an instruction (Loop1CharBody) that the optimizer emits, and it is #[doc(hidden)].

Choices to make:

  1. How a match stops. Use a linear-time engine where the pattern allows one, give each match a step budget, or have the engine poll the evaluation’s own limits.
  2. What the error is. The timeout’s and cancellation’s codes (D1012, U1003), or a new limit (U1001).
  3. How the engine change ships, since regress cannot do it today.

Decision

  1. The backtracker polls the evaluation’s limits. jlens matches through a fork of regress that takes an optional interrupt check: a callback the backtracker calls every N steps, which returns whether to stop. When it says to stop, the match returns an “interrupted” result instead of a match or no match.
    • A step is a unit of work that bounds everything between two checks: backtracks, and the instructions run between them, nested lookarounds included. The exact unit and N are settled by measurement during implementation. Targets: on the catastrophic cases, under 1 ms between two checks in a release build; on benches/, under 2 % slower.
    • As implemented in jlens-regress: a step is a failure that sends the backtracker back to its stack, or an iteration of a loop, and N is 1,024. Measured with cargo run --release -p jlens-regress --example interrupt_cost on 2026-10-11: on five catastrophic patterns, a median of 9 to 13 µs between two checks (maximum about 0.2 ms, scheduling noise included); on ordinary matches, within the noise of the run (±4 %, a few nanoseconds per call). Measured again after the rebase onto 0.12.0: the same times between checks, and the same noise on ordinary matches except one, a backreference that backtracks on every word ((\w+)\s+\1 on prose), 10 % slower than find_from against 0 % on 0.10.5. The code paths are the same; the difference comes from how the compiler inlines the backtracker once the check is in. It applies only to evaluations with a timeout or a token.
    • Measured again for 0.22 (2026-10-24): the example’s two sides are two copies of the backtracker in one binary, which the release profile (lto = true, codegen-units = 1) inlines and places anew on every change to the crate. A change that runs no differently on these patterns moved find_from by 4 to 7 %, and the interruptible side of one case by 34 % when a single file was reverted. With functions and blocks aligned (RUSTFLAGS="-C llvm-args=-align-all-functions=6 -C llvm-args=-align-all-nofallthru-blocks=5"), which takes the placement out, two revisions measure the same within 1 %, and the check costs 2 to 4.5 % on ordinary matches (the anchored one is 6 % faster with it). That is the cost this decision accepts. The 2 % target holds at jlens’s level, where cargo xtask ab measures the evaluations that match through the check (regex 2.7 % faster across the engine fixes of 0.22 item 4).
    • Measured with the engine’s benchmark (0.22, crates/jlens-regress/benches/engine.rs), whose two variants are binaries of their own: in one binary, two copies of the backtracker that both count nothing differed by up to 16 %, so the example’s comparison measured how each copy was inlined more than the check. The counter was a field in memory, and every step waited for the store of the one before: 2.5 % on average over 17 cases, 7 to 11 % on some. Each attempt now counts on a local copy, kept in a register and written back when the attempt ends or enters a lookaround: 1.7 % on average, from 4.6 % faster to 9.5 % slower. The check itself costs about 7 % on a backreference that backtracks one character at a time; the rest of the spread is register allocation, which any change to the backtracker redraws: a variant with the interrupt’s code that counts nothing is 12.8 % slower on one case and 9 % faster on another. The 2 % target holds on average; the performance page records each case.
    • jlens passes a check only when the evaluation has a timeout or a cancellation token. Without either, the match runs the unchanged code path (the check is a type parameter, so the “no check” version compiles to the current code). As with the tracer (ADR 0004), a feature that is not used costs nothing.
    • Every match that user input reaches goes through it: the regex function values (exec and next in regex.rs, which $match, $replace, $split and $contains all use) and the regex that $toMillis builds from a picture (datetime.rs). The fixed internal patterns in datetime.rs need no check.
  2. The error is the limit that stopped it. A match that the timeout stops fails with D1012, with the evaluation’s timeout as its value. One that a cancellation stops fails with U1003. These are the codes the same limits raise between steps, so callers handle nothing new and there is no new option.
  3. The fork is a workspace crate, jlens-regress, published on crates.io before jlens-core.
    • It is regress plus the interrupt API, and nothing else. The diff stays small so that it is easy to review and to rebase. It started from 0.10.5 and was rebased onto 0.12.0 on 2026-10-11 for the fixes upstream made in between: JavaScript semantics (the position restored when backtracking out of a lazy loop, i case folding, nested and negated classes, \x as an identity escape, duplicate named groups), and a nesting limit in the parser (256 levels), which turns a pattern that overflowed the stack into a syntax error.
    • It keeps the upstream licences (MIT or Apache-2.0) and says in its README that it is a fork, of which version, and why.
    • jlens builds it with regress’s prohibit-unsafe feature, so that no unsafe path runs. The workspace lint unsafe_code = "forbid" does not apply to it, because the upstream code keeps its unsafe blocks behind cfg! checks.
    • The same API is proposed upstream as an issue and a pull request at ridiculousfish/regress. The maintainer opens them. When a regress release offers an equivalent, jlens goes back to regress and deprecates jlens-regress.

No default timeout is added, in Rust, the CLI or WebAssembly. Long legitimate evaluations would start failing, and the three would behave differently. The guides keep telling applications that run untrusted expressions to set a timeout. With one set, a regex can no longer outlast it.

Alternatives considered

  • A linear-time engine (regex or regex-automata) for the patterns it can run, keeping regress for the rest. It cannot run backreferences or lookaround, so those patterns would still need the check. Its semantics differ from JavaScript’s in ways a translation would have to cover: . and line terminators, i case folding, \b and \w, and captures that JavaScript resets on each iteration of a quantifier. It would also add Unicode tables to the WebAssembly package. It is worth revisiting for speed, but it does not remove the need for the check.
  • A separate step budget with U1001, as a new limit. It would be deterministic, but it adds an option, it could reject legitimate matches on large inputs that the timeout allows, and jsonata-js has nothing like it. The timeout is already the limit for untrusted expressions. Tests stay deterministic with a short timeout and a pattern that would take minutes.
  • Static checks on the pattern (nested quantifiers, star height) with a cap on the input length. Such checks are neither sound nor complete: (a|a)*, the polynomial a*a*a*b and backreferences slip through. They would also reject patterns that jsonata-js accepts.
  • Running the match elsewhere and abandoning it at the deadline. Native threads cannot be killed, and the WebAssembly build is single-threaded.
  • Waiting for upstream instead of forking. That leaves the hole open on a timeline jlens does not control. The fork is temporary, and it lands upstream if regress accepts it.
  • Copying regress into jlens-core. That avoids a new crate, but it adds about 10,000 lines of engine and 31,000 lines of Unicode tables to the core crate. It would also mean rewriting every unsafe block to satisfy the forbid lint, which makes the copy hard to sync with upstream.

Consequences

  • A catastrophic pattern stops within the timeout, give or take the time between two checks, in Rust, in the CLI (--timeout) and in WebAssembly. A cancellation token also stops it, from another thread. In WebAssembly only the timeout can, because the page’s single thread is busy matching.
  • This differs from jsonata-js, which has no timeout of its own and hangs on such a pattern. The compatibility page documents the difference.
  • The release publishes one more crate, first: the publish order in release.yml and the release checklist in CONTRIBUTING change. cargo deny checks its licence like any dependency.
  • Upgrading regress now means rebasing the fork. The fork’s tests run every backtracking match of upstream’s suite through the interrupt API as well, and the conformance baseline and cargo xtask differential guard against changes in behaviour.
  • After 0.12.0, upstream added Regex::find_from_budgeted (commit 50bead7, unreleased as of 2026-10-11): a count of backtracks that ends the search with “budget exhausted”. It is not an equivalent: a count cannot follow a deadline or a cancellation, and a search restarted with a new budget starts over. The upstream proposal should build on it, for example with a callback when the budget runs out.
  • This ADR replaces ADR 0002’s statement that the evaluation timeout guards against pathological patterns. The rest of ADR 0002 stands.
  • Property tests generate patterns with nested quantifiers on inputs that cannot match, and check that each evaluation ends within its timeout with D1012.

0010 — Input documents converted lazily, one level at a time

Status: Accepted. Amends ADR 0003, whose consequences left room for a borrowed view of the input. Amended in 0.17: a path step reads one field of an object that has not been read (below). Amended in 0.19: the arrays and objects of a level can share one source (below). Amended in 0.24: an index reads the items of an array that it picks (below), and in 0.27, however many it picks when they are few for the array (below).

Context

ADR 0003 converts the input from serde_json::Value into jlens’s own values before an evaluation starts. The conversion visits the whole document, however little of it the expression reads. On the 24 KB document of the benchmarks (performance page, 0.8.0), the path customer.name takes:

evaluateevaluate_document
Native115 µs: 91 µs to convert, 17 µs to drop, 0.9 µs to evaluate0.9 µs
WebAssembly308 µs: 41 µs for JSON.stringify, 256 µs to parse and free2.5 µs

jsonata-js takes 2.1 µs, because it reads the JavaScript object it was given. Roadmap 0.8, item 3, asks for evaluate within 10× of evaluate_document on that case: 9 µs natively and 25 µs in WebAssembly, with no other benchmark case more than 3% slower.

Two facts bound the design:

  • Natively, the input is borrowed. evaluate takes Option<&serde_json::Value>. Owning it means cloning it, which costs about as much as converting it. A lazy value must be able to point into the caller’s document.
  • In WebAssembly, JSON.stringify alone takes 41 µs, more than the whole budget. The input must be read from the JavaScript object itself, not from its text.

The value model’s rules stay: Undefined never crosses the API, evaluations never mutate their input, a compiled Expression is Send + Sync, and a Document is converted once for many evaluations.

Decision

  1. Objects and arrays expand one level at a time. Value keeps its variants. An Array or an object’s map gains an optional pending source: the part of the input it stands for, not yet read. The first access expands it: its scalars are converted, and each of its arrays and objects becomes a new value with its own pending source. The level is then kept, so it is read at most once, and later accesses cost a branch.
    • The items of an array and the map of an object become private and are reached through accessors that expand first (items(), map(), map_mut()). The compiler then points at every place that read them directly, so none is missed.
    • A lookup expands the whole level of its object, not just one key. That costs the width of the object once, and keeps one value per field, so a field read twice is the same value. Amended in 0.17: a lookup reads its one field, and keeps it.
    • Keys go through the shared table of value::Keys, kept for the whole evaluation.
    • A value whose source was never expanded, returned as a result, is converted to JSON straight from its source (customer returns a clone of that serde_json subtree) without building jlens values.
    • The transform operator modifies only the copy that $clone makes, and $clone serializes what it copies, which expands it. A $clone that does not copy (the documented exception) modifies the expanded level, never the caller’s document.
  2. Values carry the lifetime of the input: Value<'a>. A pending source is an enum: Json(&'a serde_json::Value), which costs no allocation, or Source(Box<dyn Source<'a> + 'a>) for other inputs (item 4). The lifetime goes through the evaluator, environments and functions. Each evaluation picks one 'a:
    • evaluate and the other borrowed entry points use the lifetime of their input.
    • evaluate_document evaluates with 'a = 'static: a Document is fully expanded when it is built, as today, so it never holds a pending source.
    • Value<'a> is invariant (it holds RefCells), so a value of one evaluation never mixes with another’s. Nothing changes for threads: values were never Send, and an Expression holds no values.
    • The public audit::ValueRef<'r> keeps its single lifetime: it holds the value behind a private trait object, so tracers written today still compile.
  3. Bindings convert the same way. A variable given as serde_json::Value becomes a lazy value over it. The results of host functions and the copies $clone makes are owned, not borrowed; they stay eager.
  4. Other inputs implement a public trait, jlens_core::input::Source. One call expands one level into an opaque sink: null, booleans, numbers and strings are written as they are, arrays and objects as new sources, object fields after their key. The trait mentions no internal type, so the value model stays private. The WebAssembly package implements it over JsValue; an embedder can implement it over another JSON representation. The exact names are settled with the implementation, and cargo-semver-checks reviews them.
  5. The WebAssembly package reads the JavaScript object.
    • One call to a JavaScript helper per level returns its keys, its scalars and its nested objects, so the cost does not grow with the number of crossings between Wasm and JavaScript.
    • The helper follows JSON.stringify: toJSON is called, as for a Date; boxed primitives are unwrapped; undefined, functions and symbols are left out of objects and become null in arrays; NaN and the infinities become null.
    • The cases where JSON.stringify throws (a cycle, a BigInt, a toJSON that throws) throw the same TypeError, when the part of the input that holds them is read.
    • Document.fromJson and documents built from JavaScript objects stay eager, for repeated evaluations.
  6. Reading the input never returns an error to the code that reads it. Only a Source can fail (a JavaScript input), and making every accessor fallible would reach code that cannot fail today, such as equality and sorting. A failed expansion leaves the level empty and records the error in the evaluation; the evaluator fails with it at the next check of its limits (guardrails), before calling a host function, and before returning a result. Its code is a new U1004, whose message carries the source’s message; the WebAssembly package throws the original TypeError instead.

Implementation notes

  • Step 2 (lazy levels with the Json source) measured how the pending source is stored, because every array and object of an evaluation pays for the test, lazy or not:
    • An array keeps its items in a plain field. A lazy array keeps its source and its read items in a separate boxed part, so the other arrays test one plain field. A OnceCell around the items made evaluate_document up to 10% slower on group-by, since every access read through the cell.
    • An object keeps its RefCell map, and a lazy one fills it in place on first access; its source is a plain field and a flag. The accessors are named borrow() and borrow_mut(), like the RefCell they replace.
    • Scalars are converted directly when a level is read.
  • On the benchmark document, step 2 measured: evaluate path 1.9 µs (115 µs before); evaluate_document within ±3% of step 1; evaluate cases that read every item 0–4% slower than step 1, interleaving conversion with evaluation. Same-build runs on the maintainer’s machine sometimes differ by 25–55% on a few evaluate_document cases, so a case that moves must be measured again before it is trusted.
  • Step 3 (the Source trait, U1004 and the WebAssembly source) settled the names:
    • jlens_core::input::Source<'a> has one method, read(&self, sink: &mut Sink<'_, 'a>) -> Result<(), String>. A source stands for an array, an object, or the input itself, which writes the input as the only value of its level (nothing for undefined), so the input needs no type of its own. Expression::evaluate_source takes it, with bindings that live as long as 'a, since values of one evaluation share one lifetime.
    • Sink writes scalars (null, bool, number, string), nested sources (array, object), and the key of the next field (key). Two methods serve speed: reserve, a hint of the number of values, and json_members, which writes a level from JSON text, converted at once.
    • A failed read is recorded with the key table, in the state the lazy values of an evaluation share. The evaluator tests a flag at each step, after converting the arguments of a host function, and when the evaluation ends, whatever its outcome, so that an error caused by the empty level never hides U1004.
  • In WebAssembly, writing a level value by value costs more per value than JSON.stringify and a parse in Rust: reading the whole benchmark document so took 560 µs, against 320 µs for the conversion it replaces. The JavaScript helper therefore returns a level of more than 16 values as its JSON.stringify text, which the source writes with json_members; a text that serde_json cannot read (a lone surrogate, more than 128 levels) is read again, value by value. A smaller level returns its tags and numbers in a Float64Array, its strings and keys in one string, and its nested arrays and objects as nodes that keep their parent’s node, so that a cycle is detected as JSON.stringify detects it.
  • On the benchmark document, step 3 measured, against step 2: natively, every case within ±2%; in WebAssembly, evaluate path 7.6 µs (313 µs before), and the other cases within ±3.5% of the conversion through JSON.stringify, in one Node.js process.

Alternatives not taken

  • A borrowed variant, Value::Json(&'a serde_json::Value). Every place that matches on arrays or objects (about 90) would handle two representations, and sequences need owned arrays anyway. Lazy levels inside the existing variants keep one representation.
  • Owning the input (Rc<serde_json::Value>, with pointers into it). evaluate borrows its input, so owning it means a clone, which costs about as much as the conversion. Pointing into an Rc from a value without a lifetime needs unsafe or a self-referential type.
  • Lookups that read one key without expanding the level. Cheaper on wide objects, but a field read twice would be converted twice, into two different values. It can come later, for the Json source, if a benchmark asks for it. Taken in 0.17, keeping the fields read.
  • Reading the JSON text lazily in WebAssembly. JSON.stringify alone is over the budget.
  • A js feature of jlens-core, depending on js-sys. It ties the core library to one host; a trait serves the Wasm package and any other.
  • Fallible accessors. See decision 6.

Consequences

  • An evaluation reads only the levels its expression reaches. A path costs the width of the objects it crosses, not the size of the document.
  • Expressions that read everything (**, $string($), a filter over every item) expand every level, as the conversion did. The per-level work must stay within 3% of today’s conversion natively; in WebAssembly, per-level calls replace one JSON.stringify and one parse, and the implementation measures both before it is merged.
  • evaluate_document gains one branch per array or object it reads.
  • In WebAssembly, an input that JSON.stringify rejects fails only when the expression reads the part that JSON.stringify rejects, and the input is read during the evaluation rather than before it: a host function that changes the input object can change what is read later. The WebAssembly guide documents both.
  • The lifetime touches most signatures of the evaluator and the function library, with no change of behaviour; it lands on its own, before the lazy levels.
  • Implementation, in order: the 'a lifetime alone; the lazy levels with the Json source, for evaluate and bindings, with property tests that evaluate and evaluate_document agree; the Source trait, U1004 and the WebAssembly source, with the benchmarks of roadmap 0.8, item 3.

Amendment: one field at a time (0.17)

Context

Roadmap 0.17, item 9, measured reading a Python dict for evaluate: to look up quantity in an item of six fields, jlens read the six into a map, 534 ns, where jsonatapy looks up the one field in the dict, 66 ns. Over the 200 items of the case names over items, that was most of the 138 µs jlens took against 25 µs. The Json source pays the same way: a lookup converts every field of its object, strings included, to use one.

Decision

  1. Source gains an optional method, read_field(key, sink). It writes the value of one field of the object the source stands for, as the only value of the sink (nothing when the object has no such field), and returns true. Its default returns false: the source reads its object whole only, as before, and the evaluation reads the whole level. The Python source implements it with one lookup in the dict. The WebAssembly source does not, for now: it reads a level with one call into JavaScript, and a call per field has not been measured against it (it does since 0.26, below).
  2. The path step reads one field. functions::lookup, the step’s single site, asks the object for its field with Object::get, which reads it alone when the object has not been read whole. The Json source finds the key in its serde_json map, comparing the keys of an object of up to 16 fields rather than hashing the key (serde_json’s map hashes with SipHash). Every other access (borrow(), *, $keys, $string, comparisons, the result) reads the whole level as before.
  3. An array or object is read once; a scalar is read again. An object keeps the arrays and objects read alone in its map, with a state that says the map holds only some fields. Reading such a field again finds it there; reading the whole level later reads every field from the source, then puts back the values kept, so an array or object read twice is the same value. Scalars, the only values whose identity does not show, are not kept: keeping one costs a map, its allocations and a key, more than reading it again. A missing field is not kept either.
  4. An object that keeps a field is no longer unread. It is converted to JSON, and walked by the transform’s check for cycles, through its whole level, not as the input it stands for: an object it keeps may be one that a $clone that does not copy has changed. An object of which only scalars were read stays unread.
  5. What does not change. A level read whole is read once; cycles and deep input fail with U1004 and U1001; a source that fails stops the evaluation as decision 6 says. Errors come from the part that is read, now at the grain of a field: a Python dict holding a set fails when that field, or the whole dict, is read, and a key that is not a str only when the whole dict is.

Implementation notes

  • A first version kept every field read alone. It made the shipping rule, which reads five of the six fields of each item, 20% slower with cargo xtask ab --mode evaluate: each item paid for a map grown field by field. Making room for the whole object at the first field cured the shipping rule but took names over items from 52 to 90 µs, and at the second field it cured neither. Keeping only arrays and objects removes the map from objects whose scalars are read.
  • With evaluate on a serde_json::Value, against 2bf7c84: names over items 152 → 18.5 µs, filter + aggregate 192 → 64 µs, group-by 208 → 101 µs, the shipping rule 216 → 151 µs, the path 1.22 µs → 0.60 µs; no case slower (transform and recursion within ±1.5% over 20 rounds, as when a revision is compared with itself). evaluate_document is unchanged.

Consequences

  • A path through wide objects costs the fields it reads, not their width.
  • A scalar read several times is converted each time: a string allocates again. An expression that reads a few fields of an object, then needs it whole, reads the arrays and objects among them twice, for the cost of a lookup each.
  • A Python key’s __eq__ can run during a lookup, when a dict has a key that is not a str and whose hash collides with the key looked up. Such a dict fails when it is read whole.
  • Object gains no field: its read flag becomes a state of three values.

Follow-up: the WebAssembly package (0.26 #3)

The WebAssembly package’s source implements read_field, with a JavaScript helper that looks the field up as JSON.stringify reads it: an own enumerable field, its toJSON called with its key, a boxed primitive unwrapped, nothing for a value that JSON.stringify leaves out. A scalar comes back as a JavaScript value, and an array or object as a node, its cycle checked against the same ancestors as a level’s. A field whose getter throws, or that holds a cycle, fails when it is read, no longer when one of the fields around it is. With evaluate, path takes 4.9 µs instead of 7.3 µs, and the two indexes into 10,000 items 6.8 and 7.6 µs instead of 7.5 and 8.2 µs; the other eleven cases are within 2.1% (the median of four alternated runs of compare.mjs, each cell).

It does not reach names over items (355 against 363 µs): an array of more than 16 values is still read whole through JSON.stringify, so the fields of its items are read from lazy JSON, after every item was converted. Three variants were measured, one run each, and not kept:

  • A long array of objects as one node per item, nothing of them read: names over items 154 µs, number formatting 104 µs instead of 395, regex 416 instead of 555; but the shipping rule 1.10 ms instead of 498 µs, sort + map 1.09 ms instead of 840 µs, the transform 1.64 instead of 1.36 ms, the object constructor 673 instead of 585 µs and group-by 537 instead of 459 µs. A scalar read alone is read again at each lookup, one call into JavaScript each (the sort reads its keys at every comparison), and an item read whole costs a call of its own, where the array cost one JSON.stringify and one parse.
  • The same, with an object read whole at its second field: slower still, group-by 910 µs and the object constructor 1.06 ms. Reading a level through the helper costs more than a few fields read alone.
  • The same, with an object of scalars read as JSON text: no change (the transform 1.61 ms); what an item costs is its own call and lazy object, not the format of its level.

A long array stays read whole until there is a way to choose, array by array, between reading its items alone and reading it whole.

Follow-up: long arrays of objects (0.26 #5)

The choice is made from what the expression reads (reads(), ADR 0016), as the Java package does since 0.26 #4. evaluate turns the expression’s reads of its input into a plan once, at its first evaluation: of a value read in part, the fields read, sorted, each with its own plan, and their keys as a JavaScript array when there are at most 16. The source keeps the plan of each array and object it meets. A long array whose plan lists at most 16 fields is read by a second helper, jlensItems, when its first item is an object: in one call, each object as tag 8, its node, and the value of each field read, as JSON.stringify sees it, an array or object among them as a node. The source keeps those values, and a path step on the item finds its field there without calling JavaScript. Any other field is read alone, and the item whole as a level, so the result never depends on the analysis. An array of scalars, or one whose plan reads it whole, is read whole as before. A field of an item that holds a cycle, or whose getter throws, fails when it is read, as an object’s field does since 0.26 #3, not when the array is.

The plans of an input’s members, the fields kept and their strings are in three vectors that its levels share, so that a level still costs one allocation, and that the next evaluation reuses (up to 4,096 members).

With evaluate, the median of four alternated runs of compare.mjs per cell:

CaseBeforeAfterChange
path4.5 µs4.8 µs+7.8%
names over items337 µs52.1 µs−85%
filter + aggregate369 µs141 µs−62%
group-by423 µs195 µs−54%
sort + map789 µs553 µs−30%
strings420 µs210 µs−50%
regex519 µs252 µs−51%
number formatting369 µs100 µs−73%
object constructor547 µs312 µs−43%
transform1.26 ms1.26 ms−0.4%
recursion1.01 ms997 µs−1.3%
shipping rule467 µs302 µs−35%
index into 10,000 items6.1 µs6.5 µs+6.6%
index in a variable6.8 µs7.3 µs+6.6%

names over items is now faster than in jsonata-js (63 µs), and number formatting, which reads 20 items of 200, no longer converts the 200: every item is written with its two fields read. The cases that take a few microseconds pay about 0.3 µs more, a fixed cost of each evaluation, which the definition of done (no case more than 2% slower) did not allow and which was accepted for the gains. A micro-benchmark of those cases alone, with evaluateDocument of the same cases as a control that did not move, put it at 2% to 4%, and half of it remained in a build that made no plan at all. Five variants, measured that way, did not remove it: the helper’s keys passed only for arrays; the long arrays in a helper of their own, leaving jlensRead as it was; the members of each level in the shared vectors, not one vector per level; those vectors reused from one evaluation to the next; and the plan’s code out of line. They took the two indexes from about +6% to +1.5% in the micro-benchmark, not path.

Amendment: one allocation per member (0.19)

Context

Roadmap 0.19, item 3. Each dict of a list that an evaluation does not read cost jlens 98 ns, against 30 ns in jsonatapy, and about 40% of it was malloc and free: Sink::array and Sink::object box the source they are given, besides allocating the array or object itself (an array also allocates the part that holds its lazy items). Sink takes any type of source, so it cannot keep the sources of a level together without boxing each, or erasing their type with unsafe, which jlens forbids.

Decision

  1. A new trait, input::Sources. A value of it holds the sources of several arrays and objects, its members, and reads the member at an index as a Source reads itself: read(index, sink), and optionally read_field(index, key, sink).
  2. Sink::array_of(&sources, index) and Sink::object_of(&sources, index) write a member, taking a reference to an Rc of the sources: the array or object holds that Rc and the index (a u32), and allocates nothing more. Sink::array and Sink::object stay, for sources that prefer them: they put their source in an Rc of its own, the only member, one allocation as the box was.
  3. A lazy value stays as large as before. The origin of a lazy array or object is either JSON or an Rc of sources, 16 bytes as the boxed source was. An object keeps its index in room its layout left free; an array, in the part that holds its lazy items, which only lazy arrays allocate.
  4. The Python source writes a level’s arrays and objects as members. One value per level, made at its first array or object, holds the level’s Python value and its ancestors (the chain that detects cycles, which it replaces) and the members’ Python values, the first one inline, so that a level holding a single array or object allocates no more than before.
  5. What does not change. Cycles and deep input fail with U1004 and U1001; a member keeps its Python value, so a host function that changes the input between two reads does not change which value a member stands for; free-threaded Python is supported as before (no Python code runs while a level is read, and a dict or list is locked while it is).

Consequences

  • With Python values in, $count(items) takes 15.4 against 19.0 µs and names over items 35.1 against 37.4 µs (performance).
  • A first version added the index to the origin, which made every lazy object 16 bytes larger, those over serde_json too: names over items took 17% longer with cargo xtask ab --mode evaluate. With decision 3, no case is slower but group-by, by 2%.
  • The WebAssembly source still boxes each source: it has not been measured with members.

Amendment: one item at a time (0.24)

Context

Roadmap 0.24, item 4. An index into an array of the input read the array’s whole level: items[0].code over 10,000 items took 0.6 to 0.7 ms through a source or with evaluate, writing a lazy value for each item, against 0.67 µs against a Document, and 6.25 ms in the WebAssembly package’s evaluate, against 2.2 µs in jsonata-js. The 0.17 amendment let a path step read one field of an object; an index had no such way.

Decision

  1. Source gains two optional methods, length() and read_item(index, sink). length tells how many items the array the source stands for has, without reading them; read_item writes the item at an index below that length as the only value of the sink, and returns true. Their defaults, None and false, keep the source reading its array whole. Sources gains the same, given the member’s index. An item read alone needs the length: a negative index counts from the end, and an index out of range picks nothing.
  2. An index reads the items it picks. A predicate that is a number (items[0], items[-1]), and one built from literals alone, which gives the same value for each item (0.19 #2: items[[0..2]]), ask the array for its length and for each item they pick, which it reads alone when it has not been read whole. Over JSON, the item is taken from the serde_json array. $count reads the length too. A predicate that tests each item, an index held in a variable (items[$i]) among them, and every other access read the whole level as before.
  3. An array or object is read once, as a field is. The array keeps the arrays and objects among the items read alone, with their indexes; reading the whole level later puts them back in their places, so an item read twice is the same value. Past 16 of them, finding one would cost a comparison with each, and the array is read whole instead; a predicate that picks more than 16 items reads the level at once. Scalars are not kept. The length is asked of a source once.
  4. An array that keeps an item is no longer unread, for the reason of the 0.17 amendment’s decision 4: it is converted to JSON, and walked by the transform’s check for cycles, through its whole level.
  5. What does not change. A level read whole is read once; cycles and deep input fail with U1004 and U1001; a source that fails to read an item stops the evaluation as decision 6 says. Errors come from the part that is read, now at the grain of an item.

Consequences

  • An index into a long array costs the items it picks, not the array’s length, when the input can read one item: lazy JSON can, and so can a source that implements both methods. With cargo xtask ab, built aligned against the revision before, items[0].code over 10,000 items takes 1.31 µs instead of 618 µs with evaluate, and 1.95 µs instead of 609 µs through the program’s source; against a Document it is unchanged, 0.67 µs. Every other case is within 2% in every mode, checked over 20 rounds where a run of 10 left it above.
  • Two first versions were slower elsewhere. Reading the 16 first items of items[[0..19]] alone, then the level, took 7% longer through a source than reading the level: hence the rule above. And filter, grown by the reads alone, was inlined into eval, which made the path customer.name 3% slower; it is kept out of it.
  • The part of a lazy array that holds its pending items is 48 bytes larger, for the length and the items kept. Only lazy arrays allocate it; an array that an evaluation builds, or one of a Document, is unchanged.
  • The WebAssembly and Python packages’ sources do not implement the methods yet: roadmap 0.24 #9 and #10.

Follow-up: an index held in a variable (0.24 #5)

Decision 2 left out an index held in a variable. Roadmap 0.24 #5 counts a variable as a literal there: a predicate built from literals and variables gives the same value for each item, so items[$i] reads the items it picks, unless the predicate reads $, the item, or its input is a tuple stream, whose variables (#$i, @$o) change from item to item. Such a predicate is evaluated without an item, so none is read for it. ($i := 0; items[$i].code) over 10,000 items takes 1.97 µs instead of 2.29 ms with evaluate.

Follow-up: the WebAssembly package (0.24 #9)

The WebAssembly package’s source implements both methods: length asks the JavaScript array its length, and read_item writes one item through the helper that reads a level, which checks cycles against the same ancestors. Its arrays and objects of a level are now the members of one Sources, the list of nodes the helper returns, one allocation each instead of two. With evaluate, items[0].code over 10,000 items takes 6.7 µs instead of 6.19 ms, and ($i := 0; items[$i].code) 7.3 µs instead of 6.19 ms; the twelve other cases of the comparison with jsonata-js are between 3.6% faster and 0.4% slower (the median of four runs each).

Follow-up: the Python package (0.24 #10)

The Python package’s source implements both methods for a list and a tuple: length reads their size, and read_item writes one item, under the list’s lock as a level is read, and checks cycles against the same ancestors. A host function, or another thread, can make a list shorter after its length was read; an item past its new end is undefined. With Python values in, items[0].code over 10,000 items takes 1.3 µs instead of 413 µs, and ($i := 0; items[$i].code) 1.7 µs instead of 414 µs; the other cases of python.py speed are within 2.3% (the median of three alternated runs, both builds aligned).

Follow-up: a predicate that picks many items (0.27 #8)

Decision 3 left a predicate that picks more than 16 items reading the level, for two reasons: more items kept than that would be slow to find among them, and an array read alone and then whole pays for both. So items[[0..19]] over 200 items read all 200, and over Java maps wrote each with the fields the expression reads, to use 20: 58 µs, where 0.25.0 took 43.

Neither reason holds for such a predicate. It knows how many it picks before it reads one, so it can choose once, and the items kept are now found in a BTreeMap. What it chooses by:

  • A predicate that picks more than 16 items reads them alone when, with those kept, they are at most one item in ten of the array, and its level otherwise. One in ten is what was measured: a number read alone took about 0.58 µs in WebAssembly, the dearest of the inputs, where its level took 0.06 µs a number, so that at one in eight numbers took 8 to 19% longer there, and at one in ten none takes longer in any package.
  • An index keeps 16. A number or a variable gives one index at a time and cannot tell how many will follow, so that a loop over items[$i] would read one item in ten alone and then the level anyway. Trying the same limit there made such a loop, stopping just past it, 65 to 70% slower in WebAssembly, 20 to 31% in Java and 18 to 22% in Python on arrays of 2,000 items and more. With 16 it takes what it took.

Errors follow, as decision 5 says: an item not picked is no longer read, so one that cannot be read fails nothing.

reads() does not change. The analysis cannot say which items an expression needs: most indexes are known only at run time, it knows no types, and an array under another array is flattened, so that a position does not name one item. The evaluation can say it, at the moment it picks them.

With cargo xtask ab, built as usual, number formatting takes 35.5 instead of 44.0 µs with evaluate, −19.2%, and 39.4 instead of 46.7 µs through the program’s source, −15.8%. Against a Document, which is not lazy, it is unchanged, +0.5%, and every other case is within −1.9 and +2.5% in the three modes. In the packages, in µs per evaluation:

Packagenumber formattingBeforeAfterChange
Javaover maps57.533.4−42.0%
JavaJSON text read into maps161136−15.8%
PythonPython values37.529.7−20.8%
WebAssemblyevaluate97.692.6−5.1%

Over a longer array, the gain grows with what is not read, as picks of a tenth and of a thirty-second of it show, in µs for 20,000 items:

PackageExpressionBeforeAfter
Java$sum(records[[0..1999]].price)2,382839
$sum(numbers[[0..1999]])482389
$sum(numbers[[0..624]])456123
WebAssembly$sum(records[[0..1999]].price)4,1182,887
$sum(numbers[[0..1999]])1,2501,052
$sum(numbers[[0..624]])1,206333
Python$sum(records[[0..1999]].price)1,145521
$sum(numbers[[0..1999]])527125
$sum(numbers[[0..624]])49739.8

Amendment: a level read in case it is needed (0.27)

$distinct past 16 distinct items hashes each item whole (0.27 #6), where comparing stops at the first difference. So it reads levels that comparing would not, and with decision 6 alone a level no comparison reaches would stop the evaluation. Since 0.27 #12 this is only for items that the first fields of an object do not settle: those read what comparing reads, as the comparisons they leave out are false before anything below those fields is read. Since 0.28 the first fields follow into the level below them when the items kept share the levels above it, in half as many groups as items or fewer, as comparing an item with those that share them reads that level too; they read it with the two calls below, and a level they cannot read goes back to comparing as the hash does.

  1. Array::try_items and Object::try_borrow read a level that nothing needs yet. They give None when the source fails, record nothing, and leave the level as it was, with what was read alone of it. Decision 6 stands for every other read: the code that calls these two has another way to its answer.
  2. The hash goes back to comparing. At a level it cannot read, the items from there on are compared with those kept, by the plain reads, which fail as decision 6 says if they reach that level. So $distinct gives the same result and the same error as comparing alone, with a source too, and what the hash read of the items before cannot fail.
  3. What does change. A level that failed is read again when something needs it, the one exception to “a level read whole is read once”, and more of each item is read than before, so a source sees more calls, and a getter in JavaScript or Python runs where it did not. The WebAssembly package keeps the first exception a level throws for evaluate to rethrow: with two levels that throw, one met by the hash alone and one that comparing reaches, the error is U1004 as it should be, and the exception rethrown may be the first’s. Telling them apart needs a change to Source, which the API work can take.

0011 — Host functions call the functions they receive

Status: Accepted

Context

ADR 0006 gave host functions a JSON boundary: a function passed as an argument arrives as None, so a host function cannot apply it. Rule engines need that for helpers written in the host language that take a function: $retry($fetch, 3), $memoize(function($k) {...}), a lookup with a fallback function.

What jsonata-js 2.2.2 does, checked in benches/compare:

  • Every function argument is wrapped. A lambda, a built-in function ($uppercase), a partial application ($substring(?, 1)), a chain ($uppercase ~> $trim) and a host function all arrive as an async JavaScript function. Its length is 0 and its arity property holds the arity of the wrapped function. Only the arguments themselves are wrapped, not functions inside an array or an object.
  • Calling it applies the function as $map does: extra arguments are passed on, and the context value is null ($string called with no argument gives "null"). A lambda keeps the context and the variables of its definition.
  • It can be called after the host function returns, since it holds its environment.
  • Errors reject the promise with their codes (D3137 for $error, T2001). The host function can catch them, or let them through, which ends the evaluation.
  • Results are internal values. A sequence keeps its sequence flag, and a function comes back as the internal object ({"_jsonata_function": true, ...}).
  • There is no limit. A recursion through a host function ($f := function($n){ $apply($f, $n + 1) }) runs until the heap is exhausted.

The constraints of ADR 0006 still hold: HostFunction and Bindings are Send + Sync, the internal Value is not public, and the untraced evaluator must not get slower. Functions written against ADR 0006 must keep working.

Decision

  • A callable handle, through the call. HostCall::function(i) -> Option<Callable<'_>> gives argument i (indexed as in the arguments the function receives, after signature validation) when it is a function, and None otherwise. Arguments still arrive as None in the JSON slice: nothing changes for existing functions.
  • The boundary stays JSON. Callable::call(&self, args: &[Option<JsonValue>]) -> Result<Option<JsonValue>> converts the arguments to values and the result back, with the rules of ADR 0006: a sequence is an array or a single value, a function is None. Callable::arity() gives the arity, like the arity property in jsonata-js.
  • The handle borrows the call. It cannot outlive the host function’s call, so the evaluator it refers to is still running. In Rust the borrow checker enforces this; the WebAssembly bindings enforce it at run time (consequences).
  • A call is a callback of the evaluator, as for $map: the same path native functions use. It applies the function with the context null, counts as a level of depth, checks the machine stack, the timeout and the cancellation flag, and evaluates within the same size limits. A recursion through a host function ends with D1011.
  • Tracing needs no new event. The callback’s events come from the same evaluator, between the enter and exit of the host call’s node, so they nest under it.
  • Errors come back as Err, with their codes and positions. When the host function returns one, it ends the evaluation like any error from the expression.
  • Internally, HostCall gains a reference to the evaluator, the evaluated arguments and the environment of the call, behind a private trait object, so the type keeps its single lifetime. The evaluator is borrowed mutably through a RefCell during a call. A host function cannot reach its own HostCall from a nested evaluation (the implementation is 'static), so the borrow cannot fail; if it ever did, the call returns an error instead of panicking.

Consequences

  • Planned differences from jsonata-js, for compatibility.md:
    • Results are JSON: no sequence flag and no internal function object reaches the host.
    • A callable cannot be called after the host function returns. In WebAssembly, calling it then throws with a new U code.
    • In WebAssembly the callable is synchronous: it returns the result, not a promise. Code written for jsonata-js with await f(x) keeps working; code that calls .then does not.
    • A recursion through a host function ends with D1011 instead of exhausting memory.
  • A host function cannot pass a function to a callable, or receive one as its result: they cross as None. A public value type could lift that later, without changing this API.
  • In WebAssembly, a JavaScript host function receives a JavaScript function for a function argument, with an arity property, where it receives undefined today. A function that tested for undefined sees a different argument: the change is noted in the changelog.
  • Each call to a callable converts its arguments and its result, as host calls do. Callbacks over large values cost a copy each time.
  • The untraced hot path gains nothing beyond passing the evaluator and the environment to the host call: no new event, no check outside host calls.

0012 — The CLI on npm: a launcher package and one package per platform

Status: Accepted

Context

The jlens command comes from the release archives, cargo binstall and cargo install. Many of the people who write JSONata work in JavaScript projects, where tools are installed with npm (npm install --save-dev, npx). The npm package jlens-wasm is a library: it has no bin.

Three ways to put the command on npm:

  • A second CLI, in JavaScript, over jlens-wasm. It would have to reproduce the contract of ADR 0008 (envelopes, exit codes, standard output for data, never waiting on a terminal) and jlens lsp, and keep doing so for every change of jlens-cli. Two implementations of one contract drift.
  • jlens-cli compiled to WASI, run by Node.js. One package for every platform, but Node.js prints an experimental warning for WASI, the interpreter is slower than the native binary, and file and terminal access go through a sandbox that the CLI would have to be adapted to.
  • The release binary, one package per platform, as esbuild and Biome do: a small package with the command, whose optionalDependencies list one package per platform. npm installs only the one whose os and cpu match the machine.

The release builds five binaries (binaries.yml): Linux x86-64 and ARM64 (static, musl), macOS x86-64 and ARM64, Windows x86-64. They are attested and listed in SHA256SUMS.

Names on npm, checked on 2026-10-13: jlens belongs to an unrelated package (a JSON reader from 2018, whose command is jl); jlens-cli, jlens-cli-linux-x64, jlens-cli-linux-arm64, jlens-cli-darwin-x64, jlens-cli-darwin-arm64 and jlens-cli-win32-x64 are free; the scope @jlens does not exist.

Decision

  • Six packages, named after the crate. jlens-cli holds the command jlens; its optionalDependencies are the five platform packages jlens-cli-<os>-<cpu>, with os and cpu as Node.js names them (process.platform, process.arch): linux-x64, linux-arm64, darwin-x64, darwin-arm64, win32-x64. They are unscoped, like jlens-wasm, so no npm organization is needed. The command runs with npx jlens-cli or, once installed, jlens.
  • The binary is the release binary. Each platform package holds the binary of its archive, as built and attested by the release, never rebuilt, with LICENSE and a short README.md. The Linux packages need no libc field: the musl binaries are static and run on glibc and musl systems alike.
  • One version for all. Every package has the workspace version, and jlens-cli pins its platform packages to that exact version.
  • No install scripts. The command is a small Node.js launcher (bin/jlens.js): it resolves the binary of jlens-cli-${process.platform}-${process.arch}, runs it with spawnSync and standard input, output and error inherited, and exits with the binary’s exit code, or ends with the same signal. The binary sees the real terminal, so ADR 0008 holds through the launcher. When the platform package is missing (an unsupported platform, or an install with --omit=optional), the launcher prints which package it looked for and the other ways to install, on standard error, and exits with code 2.
  • Generated, then packed in CI. An xtask command builds the six package directories from the archives: the binaries out of the archives, package.json from the workspace version. CI packs them and installs the packed packages on Linux, macOS and Windows, then runs jlens --version.
  • Published by release.yml with provenance, after the binaries and next to jlens-wasm: the platform packages first, jlens-cli last, so that a published jlens-cli never points to a missing package. The job skips the packages whose version is already on npm, so re-running it completes a release that failed halfway through.

Consequences

  • npm install -D jlens-cli and npx jlens-cli give JavaScript projects the same jlens as every other channel, with no second implementation to keep in step.
  • Each run of the command starts Node.js before the binary, some tens of milliseconds. Programs that run jlens many times can call the binary directly (node_modules/jlens-cli-<os>-<cpu>/jlens) or install it through another channel.
  • Windows on ARM64 and other platforms without a release binary get the launcher’s error, as they get no archive today. A new target in binaries.yml adds one platform package.
  • npm and the other channels install the same command in different directories. With more than one installed, the first on the PATH runs, whatever its version; inside npm scripts and npx, a project’s own jlens-cli comes first. The installation page recommends one channel and shows how to check which jlens runs.
  • The release publishes five more packages, and NPM_TOKEN must be allowed to create them for the first release.
  • The jlens name on npm stays with its owner. If it becomes free, it could later become an alias of jlens-cli.

0013 — The VS Code extension: one package per platform with the release binary

Status: Accepted

Context

jlens lsp is a language server (ADR 0007). Neovim, Helix and Emacs start it from a few lines of configuration, but VS Code starts language servers only from extensions, and most people who write JSONata use VS Code. The extension has to answer five questions: where the server comes from, how the user points it to another jlens, which language it claims, under which name it is published, and where its code lives.

The server is the jlens binary. The release builds it for five targets (binaries.yml): Linux x86-64 and ARM64 (static, musl), macOS x86-64 and ARM64, Windows x86-64, attested and listed in SHA256SUMS. Three ways to give it to the extension:

  • A jlens found on the PATH. The extension stays small, but nothing works until the user installs the CLI through another channel, and the server’s version drifts from the extension’s.
  • A download at first start, from the GitHub release. The extension would need the network on first use (not always there, often behind a proxy), and would have to verify the archive itself before running it.
  • One VSIX per platform with the release binary, as rust-analyzer does. Since VS Code 1.61, the Visual Studio Marketplace and Open VSX serve each platform its own package (vsce package --target), and a package without a target to the platforms that have none.

VS Code’s targets include alpine-x64 and alpine-arm64. The musl binaries are static, so the two Linux archives serve both the linux- and the alpine- targets.

Other JSONata extensions, checked on 2026-10-14: on the Marketplace, bigbug.vscode-language-jsonata (a grammar, about 6,000 installs, last updated in 2023), nawed-diwan.jsonata-intellisense and Fitmavincent.jsonata-validator; on Open VSX, none. All three use the language id jsonata, the extension .jsonata and the grammar scope source.jsonata, as the editors guide does for Neovim and Helix.

Names, checked on 2026-10-14: the publisher thkprado exists on neither registry, and neither does the extension thkprado.jlens.

Open VSX publishes with an access token of an Eclipse account (ovsx publish). The Marketplace publishes with a personal access token of Azure DevOps, but retires global tokens on 2026-12-01 and recommends a Microsoft Entra ID identity instead (vsce publish --azure-credential): a managed identity, which is an Azure resource and needs an Azure subscription.

Decision

  • One VSIX per release target, with the release binary. linux-x64, linux-arm64, alpine-x64, alpine-arm64, darwin-x64, darwin-arm64 and win32-x64, each holding the jlens binary of its archive, as built and attested by the release, never rebuilt. One more VSIX, without a target and without a binary, serves the other platforms (Windows on ARM64, 32-bit ARM Linux) and uses the jlens on the PATH. No download at first start.
  • The server is found in this order: the setting jlens.server.path, then the bundled binary, then jlens on the PATH. The setting has the machine scope and is restricted in untrusted workspaces, so that a repository’s settings cannot choose which program runs. When no server is found, the extension says so once, with a link to the installation page, and leaves highlighting working. The server’s version, from its initialize answer, goes to the output channel.
  • The language is jsonata, with the extension .jsonata, the alias JSONata and the grammar scope source.jsonata, the same as the other extensions and editors. A file opened in VS Code has one language id, so a different id would split JSONata files between extensions. jlens.json is checked through a JSON Schema contributed with jsonValidation.
  • The extension is thkprado.jlens, named jlens and displayed as “jlens — JSONata”, on both registries: the publisher thkprado on the Marketplace and the namespace thkprado on Open VSX, created by the maintainer.
  • One version for all. The extension has the workspace version and is published by release.yml after the binaries, as the npm packages are (ADR 0012), skipping a version already published, so re-running the job completes a release that failed halfway through.
  • The Marketplace credential is chosen with the publishing job (roadmap 0.15 #5), among: an Entra ID managed identity federated with the release workflow (no long-lived secret, but an Azure subscription); a personal access token, which works only until 2026-12-01; or no credential, with the maintainer uploading the VSIX files attached to the GitHub release. Chosen on 2026-10-14: an Entra ID identity federated with the GitHub environment vscode of the release job. It became an application (a service principal) rather than a managed identity: it needs no subscription, so it outlives a free one. Open VSX is published to with a token for the first version, which only a token can publish, then through trusted publishing (the run’s OIDC token), so that neither registry keeps a long-lived secret. CONTRIBUTING.md says how to set both up.
  • The code lives in editors/vscode/, outside the Cargo workspace: package.json, the TypeScript client over vscode-languageclient, bundled into one file with esbuild, the TextMate grammar and the language configuration, and the extension tests (@vscode/test-electron). A cargo xtask vscode command builds the VSIX files from the release archives, as cargo xtask npm-cli builds the npm packages.

Consequences

  • Installing the extension is enough on the five release platforms: no other step, and the server always has the extension’s version. Other platforms install the CLI another way.
  • Each release publishes eight VSIX files to two registries. Seven of them hold a binary of a few megabytes; the alpine packages repeat the Linux ones.
  • With jlens.server.path or a jlens from the PATH, the server’s version may differ from the extension’s. The output channel shows it.
  • With another JSONata extension installed, VS Code uses both: two grammars for the same scope, of which one wins, and diagnostics from each server. The extension’s README says to disable the other’s language features.
  • The release needs an Entra ID tenant for the application, which an Azure sign-up creates, and a GitHub environment whose rules accept only version tags. Only a workflow run can sign in as the application, so a small workflow (marketplace-identity.yml) reads the ID the publisher takes as a member.
  • VS Code for the Web (the web target) is left out. The WebAssembly package offers the same language service, and could serve it later.

0014 — The Python package: PyO3 bindings that mirror the WebAssembly package

Status: Accepted

Context

JSONata in Python has three implementations, checked on 2026-10-15: jsonata-python 0.7.1, a port in pure Python; jsonata 0.2.5, a wrapper of jsonata-js; and jsonata-rs 0.1.4, a young Rust port of jsonata-java. jlens would bring its conformance, audits and speed to Python, where data pipelines and rules live. The package has to answer seven questions: which binding, where its code lives and under which names, which API, how a Python value is read, how threads share what the package returns, which interpreters its wheels serve, and what it leaves out.

The binding. PyO3 is the binding of Rust to CPython, and maturin builds its wheels. Both are what other Rust packages on PyPI use (pydantic-core, orjson, polars). The workspace forbids unsafe_code, and PyO3’s macros expand to code that calls CPython’s C API. A spike (PyO3 0.30.1, maturin 1.15.0, Rust 1.99, Windows x86-64) answered that question: a module with #[pyclass], #[pymethods] and #[pymodule] compiles under unsafe_code = "forbid" with no warning, and an unsafe block written in the crate is still refused. The unsafe code is inside PyO3, as it is inside wasm-bindgen for the WebAssembly package.

Reading a Python value. The WebAssembly package reads its input one level at a time through Source (ADR 0010). The spike read Python values the same way (a dict as an object, a list or tuple as an array, cycles detected through the chain of parents) and compared it with the other ways to give jlens a document. Microseconds per evaluation, best of five, Python 3.14.8, release build, on a document of items with five fields each (id, name, price, a list of tags, a nested object):

ExpressionPython values, one level at a timejson.dumps, then the JSON textParsed JSON, read lazilyDocument
1,000 items (106 KB of JSON)
items[0].name2223,872624.1
$count(items)2163,6081.30.9
$sum(items.price)1,7704,59555137
items[price > 98].id1,8424,603654135
$6,4296,0792,1032,352
100,000 items (11 MB of JSON)
items[0].name36,199450,7079,9612,480
$sum(items.price)235,319539,91590,99413,225
$846,609847,078359,145381,154

json.dumps alone takes 1,604 µs on 1,000 items and 213,087 µs on 100,000. Reading levels is 2 to 17 times faster than the round trip through JSON text when the expression reads part of the document, and costs about the same (6% more at worst) when it reads all of it, since json.dumps visits every value too. Unlike the WebAssembly package, no level is worth reading whole through JSON text. A result converted straight into Python objects costs 15% less than a result written as JSON text and read back with json.loads (6,079 against 7,133 µs for $ on 1,000 items).

Python values have no JSON form for everything. The spike stopped the evaluation with U1004, the error of a level that cannot be read, for a cycle (Circular reference detected, as json.dumps says), a set, a date or a key that is not a str, with json.dumps’s message. An int beyond 2^53 becomes the nearest number, as in jsonata-js. NaN and the infinities become null, as the WebAssembly package does with JSON.stringify.

Threads. jlens_core::Expression is Send and Sync. jlens_core::Document holds Rcs and is neither. A PyO3 class that is not Send is declared unsendable, and the spike showed what that costs: an unsendable Document used from another thread raises PanicException, which derives from BaseException (so except Exception misses it), and prints a Rust panic on standard error. Building a document once and sharing it with a pool of worker threads is a common Python pattern, so that would be a trap. Making the class Send by hand needs unsafe impl Send, which the workspace forbids. The “parsed JSON, read lazily” column is the other way: a serde_json::Value behind an Arc is Send and Sync, and each evaluation reads it lazily, 4 to 15 times slower than a Document when the expression reads the items.

Free-threaded Python (PEP 703) runs threads without the GIL. A module declares that it supports it (#[pymodule(gil_used = false)]), and its classes must then be safe without the GIL, which Send + Sync classes are. The stable ABI (abi3) does not cover free-threaded builds; PEP 803 adds abi3t from Python 3.15. The spike built three wheels of the same module: cp39-abi3 for Python with the GIL, cp314-cp314t for 3.14 without it, and cp315-abi3.abi3t (PyO3’s abi3t-py315 feature), which served Python 3.15.0 free-threaded, with the GIL disabled. Each wheel takes 0.9 MB on Windows x86-64.

A bug the spike found. A Source input 20,000 levels deep, returned whole ($ or $string($)), overflows the stack in jlens-core: the conversion of the result into JSON (Value::to_json_spending) and the serialization of $string recurse without stack::grow. $count($) on the same input works. The bug is not Python’s: a pure Rust Source reproduces it, and the Python package would expose it to any nested list.

Decision

  • PyO3 and maturin, under the workspace’s lints. The crate keeps unsafe_code = "forbid" and missing_docs, as every crate of the workspace does.
  • The crate is crates/jlens-python, in the workspace, not published to crates.io. It is a maturin project in the mixed layout: the native module jlens._jlens and a Python package jlens beside it in crates/jlens-python/python/jlens/, which re-exports the module and holds the type stubs (_jlens.pyi) and py.typed. The PyPI name is jlens (free on 2026-10-15), with the workspace’s version, in beta (Development Status :: 4 - Beta) until 1.0, as the WebAssembly package is.
  • The API mirrors the WebAssembly package’s, in Python’s style (snake_case, keyword arguments):
    • Expression(source), with evaluate(input=None, bindings=None, **options), evaluate_json(text, bindings=None, **options) (the input and the result as JSON text), evaluate_document(document, ...), evaluate_with_audit(...), register_function(name, implementation, signature=None) and source.
    • Document(value) and Document.from_json(text).
    • The options are those of EvaluateOptions: timeout in seconds (a float, as Python’s own APIs take it), max_depth, max_string_length, max_array_length, max_result_size, now (milliseconds since the epoch, a datetime or an ISO 8601 string) and seed.
    • Errors raise jlens.JlensError, a subclass of Exception, with code, position, start, end, token and value. Its offsets count code points, the unit of Python’s str, so that source[error.position] points where jsonata-js’s UTF-16 offset points.
    • evaluate returns None for an undefined result, and for null. evaluate_json tells them apart: None for undefined, "null" for null.
    • The language service (LanguageService, infer_schema) is left out: editors reach it through the language server and the VS Code extension. It can be added when a Python application asks for it.
  • evaluate reads its Python input one level at a time, through Source, as the WebAssembly package does, with the conversions above: dict (and its subclasses) as an object, list and tuple as arrays, str, int, float, bool and None; anything else stops the evaluation with U1004. The input must not change during the evaluation: a change can give a result mixing both states, or U1004, never a crash. Results are converted straight into Python objects: an integral number that fits in 64 bits becomes an int, as json.loads would give it, and other numbers a float.
  • Document can be shared between threads. It holds the parsed JSON (Arc<serde_json::Value>) and is a frozen class. Each thread converts it into a jlens_core::Document the first time it evaluates against it, and keeps that copy in a thread-local cache, keyed by a Weak reference to the JSON: a later evaluation on that thread runs at the speed of a Document. The cache drops a copy once its document is gone, at the thread’s next evaluation, or when the thread ends. Building a Document from a Python value converts it whole, with the same rules as evaluate.
  • The module supports free-threaded Python (gil_used = false). evaluate_json and evaluate_document detach from the interpreter while they evaluate, so that other Python threads run meanwhile, and attach again to call a host function written in Python. evaluate stays attached, since it reads Python objects as it goes.
  • Wheels: for each release target (Linux x86-64 and ARM64, manylinux and musllinux; macOS x86-64 and ARM64; Windows x86-64), one abi3 wheel for Python 3.10 and later with the GIL, and one abi3t wheel for free-threaded Python 3.15 and later; and a source distribution. Free-threaded 3.14 builds from the source distribution, which needs Rust. The oldest Python supported is 3.10: CPython stopped supporting 3.9 in 2025, and 3.10 is still the Python of current long-term distributions (Ubuntu 22.04). With abi3, an older floor costs one more version in the test matrix, not one more wheel; it is raised in a minor release, when PyO3 drops it or few users remain.
  • The deep-input bug is fixed in jlens-core before the binding (roadmap 0.17 #2): the conversion of results and $string go through stack::grow, with a robustness case on a deep Source.
  • Host functions written in Python (added with roadmap 0.17 #4). A callable in the bindings, or registered with register_function, is a host function: HostFunction holds the Py<PyAny> (which is Send + Sync) and attaches to the interpreter to call it. Without a signature its arity counts the positional parameters before the first with a default, as JavaScript’s length does. At the function boundary None stands for undefined, in the arguments and in the result; inside a list or a dict it is null. An exception the function raises is kept by the evaluation and raised again unchanged, with the call’s position and token added when it has none; an awaitable result fails with U1002. A JSONata function among the arguments arrives as a jlens.Function. The handle jlens-core gives borrows the call (ADR 0011) and cannot live in a Python object, so each call publishes it in a scoped thread-local (scoped-tls-hkt, whose safe API takes the place of wasm-bindgen’s borrowed closures), and the Function finds its call there by number. Called after the call has returned, or from another thread, it raises U1005.
  • evaluate_with_audit returns a dict (typed by jlens.AuditResult) with result, error, audit, explanation and explanation_text; result and error are always there, None when there is none. The audit tree and the explanation keep the JSON of the CLI (nodeCount, durationMs), with spans in code points; the options and the capture limits are in snake_case.

Consequences

  • A Python user installs one wheel of under 1 MB, with nothing to compile, on the release targets. Other platforms and free-threaded 3.14 need a Rust toolchain.
  • The Python and WebAssembly packages have the same objects, options and errors, so the book can describe them together, and an application can move between them. Where Python’s style differs (snake_case, seconds, code-point offsets), the Python chapter says so.
  • evaluate on Python values is the default and the fast path for a document evaluated once. A document evaluated many times belongs in a Document, 2 to 240 times faster per evaluation (twice as fast when the result is the whole document), at the cost of one conversion per thread.
  • Each thread that evaluates against a Document holds its own converted copy until the document is dropped. A pool of many threads using one large document multiplies its memory by the number of threads.
  • The workspace builds jlens-python with cargo build like any crate; the pytest suite needs maturin and a Python, which cargo test does not. Its CI and release steps are 0.17 #3 to #6.
  • jlens-core gains a fix for every Source input, the WebAssembly package’s included.

Amendment: mimalloc as the allocator (0.19)

Context

Roadmap 0.19, items 8 and 11. Profiled with glibc’s allocator, malloc and free took 24% to 38% of the object constructor and 30% of $count(items), where each dict of the list allocates its object; jsonatapy uses mimalloc. The jlens command has used mimalloc since 0.15, where it made glibc builds 3 to 20% faster on ten of the twelve benchmarks, and musl and Windows builds up to 3 and 2 times faster (the performance chapter). The module is loaded by the interpreter at run time (dlopen on Linux), where the space for initial-exec thread-locals is small and shared with every other module loaded so far.

Decision

  1. mimalloc is the global allocator of jlens-python, on every wheel target, and of no other library crate: a Rust application chooses its own allocator. It serves the module’s own allocations; Python objects keep the interpreter’s allocator, and no allocation crosses from one to the other.
  2. With mimalloc’s local_dynamic_tls, which reaches its thread-local state through the dynamic model, as a library loaded at run time should, rather than counting on room for the initial-exec model. Measured against plain mimalloc, it costs the smallest cases at most 0.02 µs, and reading a list of dicts 7 to 11% less.

Consequences

  • With Python values in (python.py speed, WSL, the median of three alternated runs against glibc’s allocator), ten cases take 4% to 19% less time, $count(items) 35% less; the smallest evaluations take 0.02 to 0.07 µs more, and recursion 7% more, as natively with glibc (6%).
  • A wheel grows by 60 to 70 KB (1.23 to 1.30 MB for Linux x86-64, 1.13 to 1.19 MB for Windows). The 0.18.0 wheels already took 1.09 to 1.43 MB, not “under 1 MB” as the consequences above said.
  • Every target builds mimalloc’s C sources with its own compiler, as the command’s release binaries already do: the manylinux and musllinux containers on Linux, MSVC on Windows.

Follow-up: mimalloc 2 outside Windows (0.24.1)

mimalloc 3.3.2, which libmimalloc-sys 0.1.49 bundles, crashes on glibc once the thread that imported the module has ended: a later thread’s first allocation finds a heap whose thread data is null and faults in _mi_subproc, with the local_dynamic_tls model as with initial-exec. With 0.24.0, import jlens in a thread that ends, then an evaluation in another thread, ends the interpreter with a segmentation fault. Windows and musl do not crash; the suite never saw it, since its threads live as long as the run. test_loaded_on_a_thread_that_ends loads the package on a thread that ends, then evaluates on eight new threads, in a new interpreter; it fails with the 0.24.0 wheels.

From 0.24.1 on, the package uses mimalloc 2 (2.3.2, the crate’s v2 feature) on every target but Windows, which keeps mimalloc 3. Measured in WSL, mimalloc 2, 3.3.2 and upstream’s 3.6.0 (which passes the test too, but which libmimalloc-sys has not published) are within 8% of each other on the engine’s evaluations of JSON text and documents, jemalloc 8 to 39% slower and glibc’s allocator 8 to 103%. On Windows, mimalloc 2 is up to 18% slower on JSON text, and mimalloc 3 has no such fault there. With Python values in (python.py speed, the median of three alternated runs), every case takes the same time as with 3.3.2 within 1%, or less: recursion 682 µs against 734. When libmimalloc-sys bundles a mimalloc 3 that passes the test, every target can move back to one version. The Java package’s library has the same fault and takes the same allocators; the measurements are in ADR 0021.

0016 — The fields an expression reads

Status: Accepted.

Context

An application that evaluates rules builds their input first, often from a database or a service. Knowing which fields a rule reads, it could fetch only those, and show which rules depend on a field. Roadmap 0.18 asks jlens to answer from the expression alone, for one expression or for several evaluated on the same input, and later to skip, when it parses JSON text, the fields no evaluation will read.

ADR 0010 already reads an input lazily, one level or one field at a time. That serves an input the application holds in memory. It cannot tell the application, before the input exists, what to fetch, and it reads JSON text whole.

Three facts bound the design:

  • JSONata is dynamic. A field name can be computed ($lookup($, $name)), a value can reach a function whose body is unknown, and $eval runs an expression given as a string. The answer is an upper bound: everything the evaluation may read, and as little more as the analysis can manage.
  • A wrong answer is silent. A field left out reads as undefined, and the rule gives another result without failing. The analysis needs a test over every expression jlens has, not a few examples.
  • The analysis knows no types. items.quantity reads quantity in items when items is an object, and in each of its items, at any depth, when it is an array: the path step maps over arrays (lookup in jsonata-js). The analysis cannot tell which, so its answer must hold for both.

Decision

1. What the analysis returns

Reads holds what an expression reads of its input and of each binding: a Read for the input (none when the expression does not read it), a Read for each binding it reads, by name, and a flag, every binding, that $eval sets (decision 7). A Read says what is needed of a value, whatever its type:

  • Whole: the value as it is.
  • Fields, a map from field names to their own Read: of an object, only these fields; of an array, its items, each needing the same Fields, at any depth; of a scalar, the scalar. An empty map needs the value but none of its fields: what $count, $exists and $type read.

A field absent from a map is not read. The items of an array share the node of the array because a path step does not distinguish them; the analysis never tracks indices.

Its JSON form, which the WebAssembly and Python packages and the CLI use, writes Whole as true and Fields as an object:

$sum(items[type = "book"].(price * quantity)) * (1 - $discount)

{"input": {"items": {"type": true, "price": true, "quantity": true}},
 "bindings": {"discount": true}}

Cutting a value by a Read keeps what it says: Whole keeps the value; Fields keeps an object’s listed fields, each cut by its own Read, cuts each item of an array by the same Fields, and keeps a scalar. The guarantee: an expression evaluated on its input and bindings cut by its Reads gives the same result, or the same error code, as on the whole ones. Truthiness is the reason a test reads its value whole: cutting every field of an object makes it {}, which is false.

2. The union

Reads and Read have a union: what either reads. Whole absorbs everything; two Fields merge their maps, uniting the Reads of a field present in both; the input and each binding unite the same way, and the flag is or-ed. The union is commutative, associative and idempotent. An input cut by the union of several expressions’ Reads gives each of them its result, since each Read of the union contains that expression’s own. The analysis stays per expression; an application unites the results it needs, and decision 9’s parse takes a result, not an expression, so that one Document serves several rules.

3. How the analysis works

It walks the processed tree once (Expression::ast, where % slots, stages and groups are resolved), as an abstract evaluation. The abstract value of an expression is a set of places: the input or a binding, followed by field names. Reading field f of a value extends each of its places by f; using a value, as an operand, an argument or the result, marks its places Whole. Literals and computed values (a sum, a string, a new object) have no places: whatever they were computed from was marked when they were computed. The context $ starts as the input’s place, $$ is always that place, a local variable has the places of its value, and a variable bound nowhere in the expression that is not a built-in is a binding. The value of the whole expression is used.

The places stay finite: they grow by one name per step of the tree, and decision 6 cuts every cycle through functions. Recursion goes through stack::grow, and the parser’s cap of 1,000 levels bounds the depth.

ConstructReadsPlaces of its value
A literal: string, number, boolean, null, regex—none
$—the context’s
$$—the input’s
$x, bound in the expression—those of its value
$x, bound nowhere and not a built-in—the binding x
A field name f—the context’s, each extended by f
A path a.b.ceach step with the previous step’s value as contextthe last step’s
A filter [p]p, with the item as context, usedthe step’s
A sort ^(k, …)each key, with the item as context, usedthe step’s
A group e{k: v}k, with the item as context, used; v, with the group (the places of e) as context, usednone
*, **the context, wholenone
%—decision 4
-x, + - * / %, comparisons, &, in, .., and, orthe operands, usednone
c ? t : ec, usedthe union of t’s and e’s
a ?: ba, usedthe union of a’s and b’s
a ?? ba, needed (an empty Fields)the union of a’s and b’s
[a, b, …]—the union of the items’
{k: v, …}keys and values, usednone
(a; b; …)each expression, in a scope of its ownthe last expression’s
$x := vvv’s, which $x takes
A function call, x ~> f(…)decision 5decision 5
function(…) {…}, a partial applicationdecision 6none
A transform | p | u, d |decision 6none

4. @, # and %

  • step@$v gives $v the places of the step’s value; the next step keeps the step’s context, as the evaluator does.
  • step#$i gives $i no places: it is a number.
  • % has the places of the context of the step that binds its slot: the evaluator binds the slot’s label to that context (ancestor_label). Order.Product.{"order": %.OrderID} reads OrderID of each order, not the order whole. The roadmap listed % among the constructs that read whole; following the slot costs no more than following a variable.

5. Functions

A function call uses its arguments and returns a value without places, except for the built-ins below. A built-in whose signature takes the context when an argument is missing (-) reads the context as that argument.

FunctionReadsPlaces of its value
$count, $exists, $typethe argument, needed (an empty Fields)none
$lookup(x, "k"), with a literal key—x’s, each extended by k
$append, $reverse, $shuffle, $zip, $merge—the union of the arguments’
$filter(a, λ), $single(a, λ), $single(a)λ’s body, its value useda’s
$map(a, λ)λ’s bodythose of λ’s body
$sort(a, λ)λ’s body, its value useda’s
$reduce(a, λ, init)init and λ’s body, usednone
$reduce(a, λ)λ’s body, useda’s
$evaldecision 7none
Every other built-in, $lookup with a computed key among themthe arguments, usednone
A binding: a host functionthe arguments and the context, usednone
Another function: a local variable, a computed valuethe arguments, usednone

Here λ is a lambda written as the argument. Its body is analysed where the call is, with the call’s context, and its parameters take places: the item parameter of $filter, $single, $map and $reduce, both parameters of $sort, and the array parameter, have the places of a; the index and $reduce’s accumulator have none, which is sound because what flows into them is used. Without init, $reduce starts from the first item and returns it when it is the only one, so its accumulator and its value have the places of a. When the function argument is anything else, a is used whole.

A host function can read the context of its call (HostCall::input), so a call to a binding uses the context: $tax(price) at the top of an expression reads the whole input, and price.$tax() reads price. A call through a local variable or a computed value uses the context only when a binding may have become that function (a binding used as a value) or a function of the expression takes its context (- in a lambda’s signature, or such a built-in taken as a value); the analysis decides once it has seen the whole expression.

A call to a binding reads the whole input when it stands at the top of an expression, and Whole absorbs the rest of a union: one such rule would keep a whole document for every rule evaluated on it. So an application can mark a host function as not reading the context of its call. HostCall::input then gives nothing, so the mark is a guarantee rather than a promise, and the analysis, given the bindings (Expression::reads_with), reads only the arguments of a call to a marked function. Without the mark a host function reads its context, as before. Making that the default instead would change the API, a question for the API work (ADR 0015).

Amended with the implementation (roadmap 0.18, item 2): the rows for a binding and for $reduce without init were found then.

Every built-in not in the table falls in the default row, which is always sound: a new built-in needs no entry to be safe, only to be precise. The table lives next to the catalog in functions/.

A binding or host function named after a built-in shadows it during the evaluation, but the analysis takes the name as the built-in’s. The guides say so: such an application cannot cut its input by the analysis for the rows above.

6. Lambdas and transforms

A lambda that is not the argument of decision 5’s table is analysed once, where it is defined: its parameters have no places, its context is the context of its definition (as the evaluator binds it), and its body’s value is used. Its calls use their arguments. A value passed to a function the analysis does not follow is therefore read whole, and the function’s body adds only what it reads by other ways: the context of its definition, $$, outer variables, bindings. This holds for recursion without a fixed point.

A transform is a function: what it is applied to is used (its copy is made from the whole value), and its pattern, update and delete are analysed as a lambda’s body, with a context of no places.

7. Where it gives up

The analysis reads a value whole where it cannot follow it: * and **, $keys, $string, $each, $sift, $spread, $lookup with a computed key, a value passed to a function other than decision 5’s lambdas (a lambda bound to a variable, a host function, a transform), the values of a constructed object, and the result.

$eval gives up on everything: the expression it parses can read any variable of the environment in which it is called, the bindings included. Its Reads is the input whole, every binding the expression names whole, and the every binding flag, which tells the application to keep all its bindings.

8. The API

  • Rust: a module jlens_core::reads with Read and Reads; Expression::reads(), and Expression::reads_with(&Bindings), which knows the host functions marked as not reading their context (decision 5); union on both; Read::cut on a serde_json::Value; accessors for the input, a binding and the flag; Serialize and Deserialize to the JSON form. The exact names are settled with the implementation, and cargo-semver-checks reviews them.

  • WebAssembly: Expression.reads(bindings?): Reads and unionReads(reads: Reads[]): Reads, with type Read = true | { [field: string]: Read } and interface Reads { input?: Read; bindings: Record<string, Read>; everyBinding?: true }. A JavaScript function cannot read the context of its call (this is undefined), so the package marks every one, and reads takes the bindings, as reads_with does.

    Amended with the implementation (roadmap 0.18, item 3): reads takes the bindings.

  • Python: Expression.reads(bindings=None), a dict in the JSON form, and jlens.union_reads(reads), with the stubs typing both. A Python function does not receive the context of its call, so the package marks every one, as the WebAssembly package does.

    Amended with the implementation (roadmap 0.18, item 3): reads takes the bindings.

  • CLI: jlens reads, given an expression or one or more --files, prints the JSON form on stdout: one Reads for one expression, an object keyed by file for several, or their union with --union. It follows ADR 0008: a parse error fails as check does.

    Amended with the implementation (roadmap 0.18, item 3): -f prints an object keyed by file even when it is given one file, so that a glob pattern’s output does not change shape with the number of files it matches.

9. Parsing only the fields read

Roadmap 0.18, item 4, gives Document::parse a Read (one expression’s, or a union’s) and skips, while it parses, the fields it does not list, building the document cut by it. It is kept only if the parse of wide documents measures faster; the performance page records the outcome either way.

Amended with the implementation (roadmap 0.18, item 4): Document::parse keeps its signature, and Document::parse_cut takes the Read. It is kept: a 1 MB document cut to two fields of each record parses four times as fast. The fields it skips are checked as JSON syntax only, so a number too large for a float or a lone surrogate escape passes there, where parse rejects it. In the WebAssembly and Python packages, Document.fromJson and Document.from_json take a Read, and evaluateJson and evaluate_json parse their input cut by the expression’s own reads(), without bindings, which reads at least what it reads with any. So does jlens eval, except with --explain, --audit or --trace-log, which show input values; with --filter, it parses a matching document again, whole, to print it.

Alternatives not taken

  • Reusing the language service’s typing (jlens-schema). It types an expression against a schema to complete and check it, where being approximate is harmless; it lives above the core, and decision 9 needs the analysis in the core.
  • Recording what evaluations read, through the tracer of ADR 0004, on sample inputs. It gives a lower bound, the opposite of what cutting needs: an input unlike the samples reads fields they never reached.
  • Separate nodes for an array and its items, or for indices. The path step treats an array and its items alike, and the analysis knows no types; two nodes would always be merged.
  • A flat list of dotted paths. Field names may hold dots and any character, and the tree gives such a list easily.
  • Following every lambda into each of its calls, with a cap on recursion. More precise for functions bound to variables, at the cost of an analysis that grows with the calls. It can come later if rules ask for it.

Consequences

  • The paths, comparisons, filters and aggregations rules are mostly made of are exact. Expressions that use *, **, $string, $eval or their own functions on input values read much of it whole.
  • The analysis follows the evaluator: a new construct, or a change in how one reads its operands, must change it. The default for functions keeps new built-ins sound. The test is the suite: every case evaluated on its input and bindings cut by its Reads gives the same result or error code. Property tests check that random expressions never panic, that deep ones stay within the nesting cap, the laws of the union, and that an input cut by the union of several results gives each expression its result.
  • An application that shadows a built-in with a binding or a host function cannot rely on the rows of decision 5 for it.
  • The analysis runs on demand, not when an expression compiles; its cost is linear in the tree times the places it carries.
  • Implementation, in order: the analysis, the cut and the Rust API, with the tests above (roadmap 0.18, item 2); the WebAssembly and Python packages and the CLI (item 3); the pruned parse (item 4).

Amendment: $merge needs its arguments (0.24)

The row of decision 5 for $append, $reverse, $shuffle, $zip and $merge read nothing of their arguments: what reads them is whatever uses the value. But $merge fails with T0412 on an item that is not an object, whether or not its value is used. ($y := $merge($x); a) read nothing of $x, so the bindings cut by its Reads dropped $x, and the expression gave a where the whole bindings gave T0412. A run of the property tests with PROPTEST_CASES=100000 found it (roadmap 0.24 #6).

$merge now reads its arguments as $count does, needed: a cut keeps each item and its kind, which is all the check looks at. The places of its value are unchanged. The other four accept any value.

That kept the error code, not its text: the T0412 gives the whole argument as its value, and against a Document the bindings cut by that Reads showed {"p": [...]} as {} there. The property tests found it in 0.31 (a[($y := $merge($x); 1)]), and $merge reads its arguments whole since.

Amendment: a focus and a tail call (0.24)

A run of the property tests with PROPTEST_CASES=100000 found two more expressions whose input, cut by their Reads, gave another result (roadmap 0.24 #7). Two rules change.

  • step@$v (decision 4) now needs the places of the step’s value. The path makes one tuple for each of its items, whether $v is used or not, and the next step goes on with the context once for each. $x@$v#$j read nothing of $x, so the cut bindings left it out, and the expression gave nothing where it gave the input once for each item of $x. A cut that keeps each item, as $count needs, is enough.
  • A tail call of a lambda’s body is what the trampoline evaluates: the function and its arguments, and nothing else. A group-by written on the call is not applied, in jsonata-js as in jlens: in function($y) { $zip(items){1: 1} } the value is the result of $zip. The analysis applied the group-by, so the value had no places, and items was only needed where the result held it whole. It now analyses the call alone, as the evaluator runs it.

Follow-up: a group-by on a tail call (0.24 #8)

jlens now applies a group-by written on a call in tail position, as it does outside a lambda (compatibility): tail_call_optimize leaves such a call out, as it leaves out a call with a predicate. A tail call is then the call alone, so the analysis evaluates the thunk’s body again, as it did before #7, and applies the group-by where the evaluator does: function($y) { $zip(items){1: 1} } gives one object, and needs items.

Amendment: the evaluation reads its variables by the analysis (0.27)

Until now the analysis served applications: jlens did not act on it, but for the CLI, which parses its input cut. An evaluation against a Document now does (roadmap 0.27 #5). It cannot read a variable lazily, as evaluate_with does, since a lazy value borrows the Bindings and a document’s values are 'static (ADR 0019), so it converted each variable whole. It now converts each variable as far as Reads says, with what makes that safe in the crate rather than in the application:

  • The analysis runs once for each expression, on the first evaluation with variables to convert, and is kept with it. An evaluation with none does not run it. It runs without the bindings, so it holds for all of them: a host function marked without_input only narrows what reads_with says of the input.
  • The rule above that this cannot follow, a binding named after a built-in, is checked at each evaluation. The analysis notes the built-ins the expression names, as a variable or as a field, since count() looks up a variable count, and clone when it holds a transform, which calls it by name. When a variable, a document or a host function takes one of those names, the variables are converted whole, as before.
  • Where the analysis gave up ($eval, or a variable bound where it could not follow), they are also converted whole, not only the ones it names.
  • The fields of an object are looked up, not walked, so that a wide object costs what is read of it, and come out in the order of the Read. An expression that reads an object in a way that can show its order reads it whole.

What was promised is the result and the error code, and an evaluation promises more: the same error text as well. The property test that compares evaluate_document with evaluate_with compares the text, and finds no difference, as a value that reaches an error has been used, and so read whole.

Comparing the two in the differential tests found a hole in the analysis itself, which every Reads had: a variable assigned in a branch counted as assigned from then on, so that in a ? $x := 1 : $x the second $x read nothing of the binding x, and the bindings cut by the Reads gave another result when a was false. An assignment now counts as sure only when nothing around it in its scope but blocks and assignments can leave it out. Otherwise a later read reaches the variable and what is outside it, the binding included. That is an upper bound: $f($x := 1); $x also reads the binding x.

A lazy read still does less where an expression reaches a few items of a long array: $v.items[3].price converts price of every item, since Read has no items. Roadmap 0.27 #8 looked at that, and Read stays without them. Inputs read on demand did not need them: the evaluation knows what it picks when it picks it (ADR 0010). A variable would, as it is converted before the evaluation, but items need more than a new field. A position holds only where no array lies above the array it picks from, since a path flattens those, and it would have to hold for every other use of the place, whichever of the analysis’s paths reads it, where a wrong answer is silent. The items left out would need a stand-in to keep the positions. A Read of the public API cannot say any of this without changing its JSON form. An application that reads a few items of a long variable has two ways that convert nothing: the variable as a Document of evaluate_document_with, or evaluate_with, which reads it lazily.

0017 — Results written straight into another representation

Status: Accepted.

Context

ADR 0010 reads an input in its own representation, through input::Source, so that a JavaScript object or a Python dict is not converted to serde_json first. The result takes no such path: every entry point returns a serde_json::Value, which the WebAssembly and Python packages then convert again into their own objects.

Roadmap 0.19 measured what that costs in Python (WSL, Python 3.14.8, jlens 0.18.0). The object constructor case of benches/compare/python.py, 200 objects of three fields, takes 367 µs in jlens and 195 µs in jsonatapy. Without its result converted it evaluates faster in jlens ($count(items.{...}): 155 µs against a Document, 177 µs in jsonatapy). Converting the 200 objects costs about 138 µs, in two passes:

  • Value::to_json_spending builds a serde_json::Value: a String for each key and string, and a map that hashes each key with SipHash.
  • to_py walks it and builds Python objects, with a new str for each key of each dict, which Python hashes again when it inserts it.

A string of the result costs 90 ns, against 24 ns in jsonatapy.

Three facts bound the design:

  • The size limit of a result stays. A result whose compact JSON text would be longer than Options::max_result_size, or nested more than 1,000 levels deep, fails with U1001. The limit is counted while converting, which stops as soon as it is exceeded, so a huge result never gets built.
  • Converting a result reads what the evaluation left unread. A part of the input returned as is (customer) is written straight from its source, and a level that its source then fails to read fails the evaluation with U1004.
  • The Python package evaluates a Document without holding the interpreter (py.detach), so that other threads run. Python objects can only be built while attached again, and jlens values cannot leave the evaluation: they are not Send, and they borrow the input.

Decision

  1. A public trait, jlens_core::output::Builder, builds a result one value at a time. It is the counterpart of input::Source, and mentions no internal type. It has associated types for a value, an array being built and an object being built, and methods to build null, a boolean, a number, a string, and to start, fill and finish an array or an object. The core walks the result depth first, as JSON.stringify would: undefined values and functions are left out of objects and written as null in arrays.
    • Numbers are f64, always finite. A number that is not finite is written as null, as JSON has none. The builder decides how to represent an integer: Python writes an integral number below 10^21 as an int, as it does now.
    • Keys are given as &str. The core does not say which keys are the same: a builder whose keys cost to create (a Python str, a JavaScript string) keeps them itself, in a table for the whole result. Keys repeat across the objects of a result far more than they differ.
    • The methods cannot fail. Building a value in memory fails only when memory runs out. A builder whose representation can fail (Python raises MemoryError) keeps its first failure, returns any value, and reports it once the evaluation has returned. The trait then needs no error type, and the core no way to carry one.
  2. The entry points give the result to a closure, as an output::Output. Expression::evaluate_source_to and Expression::evaluate_document_to take the arguments of evaluate_source and evaluate_document, and a closure called once the evaluation has succeeded. The closure writes the result with Output::write(&mut builder), which applies the size and nesting limits and the read failures above, and its return value is returned. The Python package calls evaluate_document_to detached, and attaches once, inside the closure, to write the result.
  3. The serde_json result goes through the same walk. evaluate and the other entry points write their result with a builder of serde_json values, private to the core. There is one walk over results, that every test and the conformance suite exercise, rather than one for serde_json and another for builders. The parts of the input returned unread are written through the builder too, from their serde_json value or their source.
  4. The packages adopt it where it pays. The Python package implements a builder over Python objects, with one str per key for the whole result. The WebAssembly package adopts it if a measurement shows a gain over building serde_json values and converting them through JSON text and JSON.parse.

Alternatives not taken

  • serde::Serialize for results. A result could implement Serialize, and the packages write it with pythonize or serde-wasm-bindgen. The size limit would have to be counted inside serialize, and its failure carried through the serializer’s error type. The serializers create each key anew, which is the cost this ADR removes, and the serde data model is wider than JSON’s. A serializer straight to JSON text could still use it later, for evaluate_json.
  • An owned result returned to the caller, written later. The result borrows the input and holds Rcs: it cannot outlive the evaluation, nor leave a thread. A closure keeps it inside the call.
  • A builder passed as an argument, without a closure. It is simpler for a caller that holds everything the builder needs. It does not serve the Python package’s evaluate_document, whose builder can only exist once the evaluation is done and the interpreter attached again.
  • An error type on the trait. It would make every method return a Result and the entry points carry a second kind of error, for failures that only running out of memory causes.

Consequences

  • An application can have results in its own representation without a serde_json pass. The serde_json entry points keep their signatures and behaviour.
  • The walk over results becomes generic: it is compiled once per builder. cargo xtask ab checks that the serde_json builder costs what the conversion it replaces did.
  • A builder does not see the evaluation’s values, only JSON: the value model stays private, as ADR 0010 kept it.
  • The tracer interface still sees results through audit::ValueRef, as JSON.
  • The WebAssembly package adopted it in 0.19. Like its input, read one level per call to a JavaScript helper (ADR 0010), its builder writes the result as a list of operations, with its numbers and strings, and one call to a JavaScript helper builds the values, decoding each key once. The object constructor case evaluates against a Document in 305 µs instead of 466 µs. evaluateJson still builds serde_json values: a builder gets each key after its value, so it cannot write the JSON text in order.

Amendment: the input returned as itself (0.25)

Context

jsonata-java returns its input object when the result is the input, as $ is, and the Java package’s results are Java objects (ADR 0021, 0.25 #5). A builder sees only JSON, so $ over Java objects read through a Source would read and copy all of them, value by value, where jsonata-java returns at once.

Decision

  1. Builder gains a provided method, input(member), called for an array or object of the input that a source wrote as a member of a Sources (ADR 0010, amended), before it is built. A builder that returns Some gives it whole; the default None builds it as before.
  2. The member (output::Member) is opaque: it tells which sources it belongs to (Member::of(&rc), by the address of the Rc the builder’s own input was read from) and its index among them. A builder that did not read the input itself never matches it.
  3. Such a value stands for the source’s object, read or not, since an evaluation never changes its input. It is not counted against the size limit or the nesting limit, as nothing of it is built, and what of it was not read stays unread.

Consequences

  • A builder still does not see the evaluation’s values: only a member’s identity.
  • The walk asks once per array or object of a source, and the default inlines to nothing, so JSON input and the other builders pay nothing. Lazy JSON is written from its text, as before. cargo xtask ab against the commit before, in the three modes, put every case within the noise: recursion took 2.9 to 3.9% longer without alignment flags and 1.4% less with them, names over items 2.6% less without and 3.7% more with, the layout of the release build moving them, and the others within 2%.
  • The C API writes such a member as its number (INPUT), and the Java package returns its own map or list: $ over Java objects returns the input itself, as jsonata-java does. The Python and WebAssembly packages could do the same; they do not yet.
  • A property test checks that a builder returning every member whole gives what evaluate gives, for any expression (crates/jlens-core/tests/robustness.rs).

0018 — A deterministic step limit

Status: Accepted.

Context

An application that evaluates expressions written by others needs a ceiling on what one evaluation may cost. jlens has three ceilings, and none is both general and reproducible:

  • max_depth (D1011) stops a deep recursion, and the size limits (U1001) stop a huge value, the same way on every machine. Loops over small arrays nested a few times pass both: $sum($map([1..1000], function($i) { $sum($map([1..1000], function($j) { $i * $j })) })) builds no array longer than 1,000 items and runs a million multiplications.
  • The timeout (D1012) stops them, but it reads the clock. The same expression on the same input passes on a fast machine and fails on a slow one, or passes natively and fails in WebAssembly. A replay, a test that compares two platforms, or a quota charged to a user cannot rely on it.
  • A cancellation token (U1003) is driven by the application, so it is as reproducible as whatever drives it. Counting the enter events of a tracer and cancelling after n of them is today’s workaround; it forces the traced evaluation, which is slower (ADR 0004).

The evaluator already has the place where such a limit belongs. Evaluator::guardrails in eval.rs checks the depth, the input’s read failures, the timeout and the token. It runs for each node the general path evaluates (eval_inner, where a tracer gets its enter event), and for each function a built-in or a host function calls back (Evaluator::callback). A few fast paths skip evaluating a node, and so skip the check, but only when no tracer is set:

  • a plain field looked up in each item of a path step (Evaluator::step), which calls guardrails in place of the step’s evaluation;
  • = and != with a string literal, which calls literal_guardrails in place of the literal’s evaluation;
  • a literal key of a group (Evaluator::group and the single-item object constructor), which checks nothing for the key;
  • a constant predicate (filter_constant), evaluated against the first item only instead of once per item.

A prototype that decrements a counter at each check measured no cost (cargo xtask ab: every case between 3.4% faster and 1.3% slower than HEAD, which is noise). The same prototype found that a timeout costs a clock read at every step: $sum($map([1..300000], function($x) { $x * 2 + 1 })) took 189 ms with jlens eval --timeout against 127 to 153 ms without (Windows).

Choices to make:

  1. What a step is, so that the count is the same on every machine, with or without a tracer, whatever the optimizations.
  2. What a regular expression costs, since one match can backtrack for years (ADR 0009).
  3. The error, and what the limit does not bound.
  4. Whether counts may change between versions, and whether an evaluation reports its count.
  5. How the counter changes the timeout.

Decision

Options::max_steps: Option<u64> (builder Options::max_steps(n)), with no default: like the timeout, a limit an application does not set changes nothing.

  1. A step is a check of the evaluation’s limits on the general path. Concretely:

    • each node the general path evaluates: one call to eval_inner, which is one enter event for a tracer;
    • each function called back through Evaluator::callback: by a built-in that takes a function ($map, $filter, $sort, $replace with a function, …) and by a host function through its Callable (ADR 0011). The body of a lambda called back then counts its own nodes;
    • one step for each check that the regular expression backtracker makes (point 2).

    The fast paths charge the steps they skip, so that the count is the one the general path would take:

    • the field looked up in each item charges one step, as the evaluation of the Name node would (it does today, through guardrails);
    • = and != with a string literal charge one step for the literal (they do today, through literal_guardrails);
    • a literal key of a group charges one step for each item it is looked up for;
    • a constant predicate charges, after its one evaluation, the steps of that evaluation once more for each further item. The predicate gives the same value for each item and reads nothing from it, so its count is the same for each.

    $eval runs in the same evaluator, so the text it evaluates spends the same budget, and parsing that text costs no step. A tail call run by the trampoline counts the nodes of the body it evaluates, like any other evaluation. A budget of n allows exactly n steps: the evaluation that takes n steps succeeds with max_steps(n) and fails with max_steps(n - 1). A fast path that charges several steps at once fails when fewer remain, so the outcome at any budget is the general path’s.

  2. A regular expression costs one step per 1,024 steps of the backtracker. The backtracker of jlens-regress already counts its own steps and calls an interrupt check every INTERRUPT_INTERVAL (1,024) of them, counting afresh for each search (ADR 0009). With a step limit set, every match takes the interruptible path, as it does with a timeout or a token, and each check charges one step. A search that backtracks less than 1,024 times costs nothing beyond the node that called it. The backtracker’s count depends only on the pattern, the text and the start, so it is the same on every platform (memchr finds the same positions with or without SIMD). A catastrophic pattern therefore stops under a step limit alone, about every 10 µs of matching per step charged (ADR 0009’s measurements).

  3. The error is U1006, with the limit as value: “The evaluation exceeded its budget of {{value}} steps”. It is a new code because an application must tell an exhausted budget from a size limit (U1001, which carries only a message) without reading the message, as it already can for D1011 and D1012; U1005 is taken. The rule “limits use U1001” of AGENTS.md becomes “size limits use U1001; the step limit uses U1006”. The error’s position is the node being evaluated when the budget ran out, which, after a fast path charged in bulk, may be an enclosing node, and may differ with a tracer. The code and value are what is reproducible.

    What the limit does not bound is the work inside one step, which the size limits already bound: a range ([1..n], up to max_array_length items), $sort without a function (its comparisons), $string and the conversion of the result, deep equality, $join, $reverse, $distinct, reading the input and parsing a Document. The work a host function does in its own code is the application’s to bound; only its calls back count. Under a step limit, the time of one evaluation is bounded by the steps times the largest step, not by the steps alone.

    Reproducible across platforms means within the other limits: the default max_depth is 50,000 natively and 500 in WebAssembly, and the stack can run out at different depths. An application that needs the same outcome everywhere sets max_depth too, and the guides say so. With a timeout and a step limit set, whichever is reached first stops the evaluation; only U1006 is reproducible.

  4. Counts change only on purpose, and are reported by audits.

    • The table test of exact counts (#2) makes any change visible in review. A version that changes counts says so in its changelog, under its own heading, with the cases that changed. Before 1.0 that is not a breaking change; the API work (ADR 0015) decides what 1.0 promises. An upgrade of jlens-regress can change the counts of regular expressions, and is reviewed the same way.
    • An evaluation does not return its count: the evaluate* methods keep their return types until the API work settles the API. The audit header gets a steps field, the steps the audited evaluation took, which equal the untraced count by point 1. An application measures an expression with an audit and sets its budget from that; the Wasm and Python audit types gain the field with their maxSteps / max_steps (#4, #5). Whether 1.0 returns the count of every evaluation, for a quota that charges what was used, is a question for the API work.
  5. The counter paces the timeout. The cancellation token, an atomic load, is still read at every step. The clock is read only every N steps of the same counter. Proposed: a mask on the remaining count. Settled in #3: the counter counts down to the next checkpoint, the end of the budget or, with a timeout, the next read of the clock, and the rest of the budget waits in a reserve. A step then costs one comparison, as without a timeout, and the checkpoint is the branch already taken when the budget runs out. A mask was measured too: the fast paths spend several steps at once and can step over every multiple of N, and testing for that on each step made two cases of the workload 5% slower. N is 256. Target: the $map above with a timeout within 2% of the time without one, natively and in WebAssembly; measured, 0.8% natively (47% before) and 1.3% in WebAssembly (149% before). A timeout then fires up to N steps late, which is at most N times the largest step; regular expressions keep reading the clock at each of their checks.

Alternatives considered

  • Counting only the general path, with the fast paths free. Simpler, but the count would depend on the tracer (a traced evaluation takes the general path) and on every future optimization: the audit could not measure the budget, and a faster release would change every count.
  • Weighted steps, charging a range or a sort in proportion to its size, closer to CPU time. The weights are arbitrary, every built-in would need one, and the size limits already bound the work inside a step. A count of evaluations is simple to explain and to keep exact.
  • The tracer workaround, counting enter events in the application. It already works but forces the slower traced path, misses callbacks of built-ins and regular expressions, and every binding would reimplement it.
  • Reusing U1001 with a message, or D1012. An application could not tell a budget from a size limit, or from a clock, without matching messages, which AGENTS.md forbids.
  • Returning the count from every evaluation now. It changes the signatures of every evaluate* method in Rust, Wasm and Python before the API work decides the API.
  • Fuel from the runtime, as wasmtime meters WebAssembly instructions. It exists only for one runtime, not natively nor in browsers, and instruction counts change with the compiler.

Consequences

  • A loop that the depth and size limits let through stops with U1006 at the same step on every machine, natively and in WebAssembly, with or without a tracer, including inside a catastrophic regular expression.
  • Without a limit the untraced path does one more decrement and comparison per step, which the prototype measured as noise; #2 confirms it with cargo xtask ab, against HEAD and with --b-max-steps, no case more than 2% slower.
  • With a step limit set, matches take the interruptible path of jlens-regress, measured in ADR 0009 as within the noise except one backreference case (10% slower).
  • The fast paths gain a charge each, and every future fast path must charge what it skips: the test that runs every case of the suite with and without a tracer and compares the counts catches one that does not.
  • jsonata-js has no such limit; the compatibility page lists U1006 next to the timeout.
  • U1006 joins error.rs and the generated error page; AGENTS.md changes as point 3 says.

0019 — Documents serialized straight from Rust values

Status: Accepted.

Context

An application that embeds jlens-core and keeps its state in Rust types (structs of strings, numbers and small lists) has one way to evaluate against that state: build a serde_json::Value (serde_json::to_value, or json!) and convert it with Document::new. When the document is rebuilt often, from a state that changes between a few evaluations, that double conversion costs more than the evaluations. One application measured it, rebuilding a document of about 10 objects of 20 fields and evaluating it 1 to 10 times: building the serde_json::Value took 35–40% of its time, Document::new 15–18%, the evaluations much less than both.

crates/jlens-core/benches/host_state.rs reproduces the case: ten records of twenty fields, rebuilt at each iteration, then the first 1, 4 or 10 of ten small expressions (filters, sorts, [0]). Windows, release, jlens 0.20.0 with the prototype of this ADR:

Building the documentµs
serde_json::to_value alone22.3
to_value + Document::new (today)43.7
serde_json::to_string + Document::parse35.8
Document::from_serialize (this ADR)17.9
Building and evaluating, µs1410
to_value + Document::new + evaluate_document (today)43.051.672.1
Document::from_serialize + evaluate_document19.328.248.7
to_value + lazy evaluate25.141.070.4
evaluate_source, a Source written over the state3.820.556.0

Every path gives the same document and the same results (the benchmark checks it before it measures).

The serde_json::Value costs a String for every key of every object, an IndexMap that hashes each key, and a String for every string; Document::new then allocates each string again, interns the keys and builds its own maps. Most of that is copying from one tree into another.

Decision

  1. Document::from_serialize<T: ?Sized + Serialize>(value: &T) -> serde_json::Result<Document> serializes a Rust value straight into the internal representation, through a serde::Serializer private to jlens-core.
  2. Its contract is Document::new(&serde_json::to_value(value)?): the same document, and an error wherever to_value fails. Property tests check it on arbitrary serde_json::Values (which implement Serialize), and a unit test on the shapes serde derives: enums of each kind ("Unit", {"Variant": …}), newtype and unit structs, Option, tuples, char, f32, maps keyed by numbers and booleans.
  3. Key order is the order of serialization: a struct’s fields in declaration order, a map in its iteration order (sorted for a BTreeMap, unspecified for a HashMap, as with to_value). A repeated key keeps its first position and takes the last value, as a serde_json::Map with preserve_order. The order no longer depends on that feature: the serializer writes the internal map itself. Keys are shared through the document’s table of keys, as Document::parse shares them, so struct field names are not allocated per object.
  4. Numbers become f64, as everywhere in jlens: i64 and u64 with as (beyond 2⁵³ they round, as Document::new rounds them today), f32 widened exactly (0.1f32 is 0.10000000149011612, as in to_value). NaN and infinities become null, as serde_json writes them. float_roundtrip plays no part: it governs parsing text, and no text is parsed. The rare paths go through serde_json itself so that they follow its features: 128-bit integers (out of the i64/u64 range: serde_json’s error, or a number with arbitrary_precision), keys that are not strings (numbers and booleans become their text, finite floats as serde_json formats them), and serde_json’s private tokens for arbitrary_precision numbers and RawValue.
  5. What JSON cannot represent fails, with the serde_json::Error that to_value gives: a map key that is a unit, an option, a sequence, a map or bytes (“key must be a string”), a NaN or infinite float key, a 128-bit integer out of range, and any error a Serialize implementation raises (S::Error::custom). Nothing is built on an error. Bytes as a value become an array of numbers, as in serde_json.
  6. One difference: nesting. A value nested more than 1,000 levels deep (MAX_NESTING) fails, where to_value would recurse until the stack overflows. The serializer grows the stack (stack::grow) on the way, as every recursive walk over values does.
  7. The error type is serde_json::Error, the one Document::parse already returns. No new public type: the API gains one function.

Alternatives not taken

  • An incremental builder (DocumentBuilder::object(), .field(key), .array(), …). It builds the same values with the same operations, so it would not be faster than a serializer that serde monomorphizes for each type, and it needs much more API to keep until 1.0: a builder type, its states, what a field without a value or an unclosed object means, its errors. The host also writes one call per field, where #[derive(Serialize)] writes none. A host that wants to write field by field already can, with input::Source.
  • Document::from_source(&dyn Source): reading a Source eagerly into a document. It reuses a public trait, but needs a hand-written source per type, and a Source writes its arrays and objects lazily (Sink::array), so the document would force every level. It would cost what from_serialize costs, for more code in the host.
  • evaluate_source alone, without a document. Already public, and the fastest for one to four evaluations (3.8 and 20.5 µs), since it reads only the levels and fields an expression reaches. But each evaluation reads again what it needs, so it falls behind a document by ten evaluations (56.0 against 48.7 µs), and it needs a hand-written Source (about 120 lines in the benchmark). It stays the answer for an application that evaluates once per state; the guide should say so.
  • serde_json::to_string + Document::parse. Needs nothing new and is 18% faster than today (35.8 µs against 43.7), but still twice as slow as from_serialize: it writes and parses text. It is the workaround for 0.20.

Consequences

  • The serializer is about 600 lines, most of them the methods serde::Serializer requires. serde 1 is stable, and jlens-core already exposes serde_json types, so a Serialize bound adds no dependency to the API that 1.0 will keep (ADR 0015 lists it among the stable items).
  • The benchmark host_state joins the workload, with host build and host rebuild on the performance page.
  • A later step could serialize only the fields some expressions read, as Document::parse_cut parses them (ADR 0016): a struct field the Read leaves out would not be serialized at all. Not part of this decision; measured if an application asks for it.

Variables of evaluate_document

Since 0.27 it converts what the expression reads of each (ADR 0016); what follows is why it had to, and the decision of 0.21.

evaluate_document converts each variable of its Bindings whole, at every evaluation (Value::from_json), where evaluate_with and evaluate_traced read them lazily (Value::lazy, ADR 0010). It cannot do the same: a Document holds a Value<'static>, and Value<'a> is invariant in 'a (its objects are RefCells, its sources dyn Sources<'a>), so an evaluation against a document runs at 'static, and a lazy value cannot borrow the Bindings. A safe conversion of the document to a shorter lifetime would copy it whole.

The benchmark measures what that costs: a record of twenty fields read through a variable ($self.score > 50 and $self.active) takes 3.5 µs, the same record read from the document (items[3]…) 1.0 µs. The 2.5 µs are the conversion of the record, at each evaluation.

What would remove it is a variable whose value is already a document, bound without converting (an Rc clone), with a way to take a part of a document as one ($self = the fourth record). Bindings cannot hold a Document (it is Send + Sync, a document is not), so that is new API of its own, decided separately (roadmap 0.21 #2), below.

Decision (0.21)

  1. Document::pointer(&self, pointer: &str) -> Option<Document> takes a part of a document, named by a JSON Pointer (RFC 6901) with the rules of serde_json::Value::pointer: "" is the whole document, ~1 and ~0 stand for / and ~, an array index is digits without a leading zero, and anything else (-, a missing field, a step into a scalar) is None. The part is an Rc clone of the value it names: it shares the document’s values, and nothing is copied.
  2. Expression::evaluate_document_with(&self, document, variables: &[(&str, &Document)], bindings, options), and evaluate_document_with_to, which writes the result with a builder. Each pair binds a name (without $) to a document, as an Rc clone. A slice of pairs, rather than a new type of document variables, keeps the API to two methods and no type; evaluate_document and evaluate_document_to keep their signatures and call them with no pairs.
  3. Precedence. A name of variables takes the place of a variable or a host function of the same name in bindings, and a later pair the place of an earlier one, as a later Bindings::var replaces an earlier one. The evaluator binds the host functions before the variables to give that order; the names of a Bindings are distinct, so the other entry points are unchanged.
  4. Transforms. A bound document is input like the document itself: the transform operator modifies only the copy $clone makes, so $self ~> |$|{…}| leaves the document and its part as they were. Tests check it, and the property test checks the documents after every evaluation.
  5. The WebAssembly and Python packages do not get it in 0.21: the friction came from a Rust host, and each package binds its own documents and variables. An item of its own when one is asked for.

Measured with host binding (Windows, release): the record through a variable of Bindings takes 3.18 µs, bound to its part of the document 0.42 µs, read from the document (items[3]…) 0.79 µs. A bound document is faster than the path, as a variable is looked up where items[3] steps through the document and filters its items.

0020 — jlens-regress is jlens’s own fork of regress

Status: Accepted. Supersedes decision 3 of ADR 0009 where it makes the fork temporary; the rest of ADR 0009 stands.

Context

ADR 0009 made jlens-regress, a fork of regress 0.12.0 (upstream commit aae35de) with interruptible matches, a temporary crate. The interrupt API was to be proposed upstream as an issue and a pull request. When a regress release offered an equivalent, jlens was to go back to regress and deprecate the fork. Until then, upgrades were to be rebases of the fork onto new upstream versions.

What happened since, as of 2026-10-24:

  • The proposal has no answer. In regress#140, a request for a backtracking limit, the maintainer said in February 2026 that they were open to one if it cost nothing when no limit is set. On 2026-10-11 jlens described its fork there, which does exactly that, and offered to adapt it into a pull request. The comment has had no reply.
  • A pull request is not an option. regress’s README has a section “No AI slop”. jlens is developed with AI assistance, and its fork was written that way. jlens respects the policy and does not send code upstream.
  • Upstream moves, in the code the fork changes. regress has 22 commits after aae35de, none released. Among them: Regex::find_from_budgeted, a count of backtracks that now aborts the whole match when it runs out (still not a deadline or a cancellation, as ADR 0009 explains); fixes to class sets with the v flag, to backreferences to duplicate named groups, and to a hang in certain nested loops; and a reorganization of the backtracker (classicalbacktrack.rs, +137 −50 lines), the file where the fork’s interrupt lives. The next rebase would redo the interrupt on a backtracker that has changed, and measure its cost again.
  • The crate is published. jlens-regress has been on crates.io since jlens 0.6.0, published first by every release, with the version of the workspace.

Choices to make:

  1. Whether the fork stays temporary, waiting for upstream, or becomes jlens’s own.
  2. How upstream’s fixes reach it.
  3. What changes of its own it takes.
  4. Its name.

Decision

  1. The fork is jlens’s own, with no plan to go back to regress. jlens no longer waits for an upstream equivalent, and no longer plans to deprecate the crate when one comes. If a regress release ever offers an equivalent, going back is weighed like any change of dependency: on what it offers (a deadline and a cancellation inside the match, no cost when unused) and on its cost on benches/, not as a promise kept.
  2. Upstream fixes are ported, not rebased. The fork stays on regress 0.12.0 plus the upstream commits jlens ports one by one.
    • What is ported: fixes to JavaScript semantics, hangs, panics and soundness, with the tests upstream adds for them. Performance changes only when cargo xtask ab shows a gain and the interrupt_cost example shows the interrupt still within ADR 0009’s targets. Upstream’s own features (find_from_budgeted, say) are ported only when jlens needs them.
    • How: each port is a commit that names the upstream commit it ports. The fork’s README lists the ported commits and the last upstream commit reviewed.
    • When: when regress publishes a release, and otherwise once per jlens minor version, as an item of its plan.
  3. The fork’s own changes stay few. It takes what jlens needs from its regex engine: the interrupt, and fixes to bugs that jlens’s fuzzing, differential tests or users find. They are marked jlens-regress in the code, as now. The diff to upstream stays small, because a small diff is what keeps ports cheap. Larger work on the engine (speed, a linear-time path) is not done in the fork.
  4. The name stays jlens-regress, and the library stays regress. It follows the jlens-* names of the other crates and says what the crate is. A rename would publish a new crate and deprecate a published one, for no gain to its users.

Bugs in the fork are reported at jlens. When one also affects regress, its maintainer may be told in an issue, written by a person. The fix in the fork does not wait for upstream.

Alternatives considered

  • Keep waiting for upstream and keep rebasing. The fixes arrive either way, by porting, and without redoing the interrupt on each reorganization of the backtracker. Waiting has no date, and the pull request it waits for cannot be sent.
  • Go back to regress with find_from_budgeted. A count of backtracks cannot follow a deadline or a cancellation (ADR 0009). It is also unreleased.
  • Another ECMAScript engine. corvus-regex-ecma262 was created on 2026-10-20, has a single author and no record yet on WebAssembly or interruption. fancy-regex, the other Rust engine with backreferences and lookaround, follows Perl’s semantics rather than ECMAScript’s (ADR 0002).
  • A shorter name. Discussed above: the gain is cosmetic, the cost is a second published crate.
  • Copying the fork into jlens-core. Rejected for the reasons ADR 0009 gives: tens of thousands of lines in the core crate, and unsafe blocks under its forbid lint.

Consequences

  • The fork’s README no longer says that it will be deprecated, and asks for every problem to be reported at jlens.
  • The first port reviews the 22 upstream commits after aae35de.
  • Nothing changes for users: the crate, its name, its API and its version scheme stay as they are. The version scheme changed in 0.36: see the amendment below.
  • Replacing the fork by an engine of jlens’s own stays possible. It would take its own ADR.

Amendment: a version of its own (0.36)

Context

Every jlens release published jlens-regress with the workspace’s version: 34 versions up to 0.35.0, most of them with no change to the crate. A crate outside jlens uses it alone, pinned to one version, and reviews each new pin; every jlens release gave it a version to review that changed nothing.

Decision

  • The crate has a version of its own, in its manifest, raised only when what it packages changes, apart from its README. The regress entry of the workspace’s dependencies asks for that version, so jlens builds and publishes against the newest.
  • Before 1.0 the version is read as Cargo reads it: the patch for a fix or an addition, the minor for a break. cargo semver-checks checks it against the last version on crates.io, as it does the other library crates.
  • cargo xtask regress-version compares the crate packaged from the tree with the one crates.io has at that version. It fails when they differ: the crate changed and its version was not raised. CI runs it on each push. The release workflow runs it before it publishes, and publishes the crate only when crates.io does not have its version.
  • The README is not compared, so that a review of upstream commits that ports none publishes no version; it ships with the next one.

Consequences

  • A jlens release that changes nothing in the fork publishes no version of it, and the changelog names the fork’s changes, jlens-regress, under the jlens release that publishes them.
  • The fork’s version no longer says which jlens it came with: 0.35.0 was the last to match.

0021 — The Java package: a C API called through Panama

Status: Accepted (2026-10-25), after the spike at the end. The context below is as it was proposed; the spike’s results led to the decision.

Context

JSONata on the JVM has two implementations: jsonata-java (dashjoin), a port of jsonata-js in pure Java, and JSONata4Java (IBM), an implementation on ANTLR. jlens would bring its conformance, audits, schemas and speed to Java, where rules engines and integration services live. As with Python (ADR 0014), the package would be bindings over jlens-core, not a second implementation: one engine, one conformance baseline, one changelog.

The oldest Java served is 25, the current long-term release. Java 21 is left out. The package has no users to keep yet, and 25 gives it the Foreign Function and Memory API (Panama, JEP 454, final since Java 22) with no preview flag. Three ways reach the JVM without rewriting the engine:

  • Panama: jlens-core compiled as a native library per platform, with a C API (extern "C" functions), which Java calls through Linker and MethodHandles.
  • Chicory: jlens-core compiled to WebAssembly and run by Chicory (1.7.5, 2026-03-24), a WebAssembly runtime in pure Java (Java 11 and later, no native dependency). Chicory has an interpreter, a compiler to JVM bytecode at run time, and one at build time (chicory-compiler-maven-plugin) that ships the module as .class files.
  • JNI: the native library called through the Java Native Interface, with the jni crate (0.22.4, 2026-03-16).

Panama and Chicory can share their Rust side. One C API crate compiles natively for Panama and to wasm32-wasip1 for Chicory. The exported functions are the same, and so is the way bytes cross the boundary (below). Each Java backend is then a thin layer that moves bytes, either through a MemorySegment or through Chicory’s Memory. Both sit behind one Java API. JNI needs glue of its own on both sides: Rust functions that receive a JNIEnv, and Java native methods. It cannot share that glue with a WebAssembly build. Its advantage was serving Java 8 to 21, which the floor of 25 no longer needs. So JNI is weighed only as the fallback if Panama fails the spike.

All options share the Java API. It mirrors the WebAssembly and Python packages: Expression, Document, the options of EvaluateOptions, host functions, audits, and a JlensException that carries the JSONata code, position, start, end, token and value. Java strings are UTF-16, so error offsets mean what they mean in jsonata-js, with no conversion for the user. Records and sealed interfaces type the results: an AuditNode is a sealed hierarchy, and the options are a record with a builder.

The C API and unsafe_code = "forbid"

The exports take #[unsafe(no_mangle)], which the workspace lint refuses. No generator writes them for us, as wasm-bindgen and PyO3 do. Two ways out:

  • An exception in the C API crate only. forbid cannot be lowered by an inner allow, so the crate declares its own lints instead of workspace = true: the workspace’s, with unsafe_code = "deny". The exports module alone carries #[allow(unsafe_code)]. That allow covers the bodies of the module’s functions too, so a macro_rules! writes each export as one call to a safe function, and a test checks that unsafe appears nowhere in the crate’s code but in that attribute. The spike measured both halves (below).
  • A small proc-macro crate that writes the exports. ADR 0014’s spike showed that code expanded from another crate’s macro does not trip the lint. That hides the exception rather than states it, so the first way is preferred.

The rest of the C API needs no unsafe. Rust never dereferences a pointer it is given:

  • Buffers are Rust’s. Java asks for a buffer of n bytes and gets a handle and the buffer’s address, as integers. It writes the input there: through MemorySegment.ofAddress(address).reinterpret(n) on the native build, and through Chicory’s Memory at that offset on the WebAssembly build. Rust then reads its own Vec<u8>, found by the handle. Results come back the same way.
  • Host functions are registered once as function pointers (Panama upcall stubs, or Chicory host functions imported by the module), typed extern "C" fn in Rust.

The boundary

Panama calls the engine directly. An input crosses as UTF-8 JSON text, written into a Rust buffer as above; Jackson or toString writes it on the Java side. Reading Java objects one level at a time through Source (ADR 0010) is possible with upcalls, one per level read. Its cost against the JSON text is the spike’s first question, since ADR 0014 found reading levels 2 to 17 times faster in Python when the expression reads part of the document.

Chicory sees only the module’s linear memory, so its input is JSON text, copied into that memory. A Source would need one imported call per level read, from WebAssembly into Java.

On both, a Document parsed once avoids that cost for an input evaluated many times.

Threads

jlens_core::Expression is Send and Sync. jlens_core::Document holds Rcs and is neither. Java servers share objects between threads as a matter of course, and on 25 they run requests on virtual threads.

Panama can reuse ADR 0014’s design. The Java Document holds the parsed JSON behind an Arc, each OS thread keeps its converted jlens_core::Document in a thread-local cache, and one Expression serves every thread. A virtual thread in a downcall is pinned to its carrier (the OS thread under it) until the call returns. So the cache holds one copy per carrier, a small pool, not one per virtual thread. A host function written in Java runs while its virtual thread is pinned: if it blocks on I/O, it holds its carrier for that time, which the Java chapter would say.

Chicory gives each WebAssembly instance one linear memory, which only one thread may use at a time. The module is Java code, so nothing is pinned. A pool lends an instance for each evaluation, and each instance parses its own copy of the expression and of each Document. Memory grows with the pool. Whether an instance can be cloned from an initialized one, instead of being instantiated again, is a spike question.

Limits and robustness

Panama runs on the calling thread’s native stack, the carrier’s for a virtual thread. stack::grow (stacker) extends that stack as it does natively, so the native DEFAULT_MAX_DEPTH of 50,000 applies. A thread created with a small -Xss is a case for the robustness tests, as musl threads were (see the musl note of the Python chapter).

Chicory runs the module’s frames on the JVM’s stack in compiled mode, and jlens cannot measure that stack. This is the situation of the WebAssembly package in V8, where DEFAULT_MAX_DEPTH is 500 for that reason. The limit for the JVM would be measured, and a StackOverflowError in the middle of an evaluation leaves the instance’s state (its stack pointer, its allocator) undefined: the instance is dropped. Linear memory caps a module at 4 GiB (wasm32), which bounds the size of a document.

Timeouts read the clock (web_time). On wasm32-unknown-unknown that crate calls JavaScript’s performance.now() through wasm-bindgen, which Chicory cannot provide. The Chicory build targets wasm32-wasip1, whose std::time reads the clock through WASI, and Chicory implements WASI preview 1. Whether rustc links that target with --stack-first, as stack::exhausted assumes, is a spike question.

Native access (JEP 472)

On Java 24 and later, Panama’s restricted methods (Linker.downcallHandle, MemorySegment.reinterpret) and System.load print a warning on standard error, once per module, unless the application is started with --enable-native-access=<module>. That is io.github.thkprado.jlens when the JAR is a named module, and ALL-UNNAMED on the class path. A later release will refuse that access by default (IllegalCallerException). The Enable-Native-Access manifest attribute only takes effect in the JAR launched with java -jar, not in a library’s JAR. A user of the native package therefore adds the flag to their launch command. A user of Chicory does not.

Distribution

Panama (as JNI would) ships the native library of every release target inside the JAR: Linux x86-64 and ARM64 (glibc and musl), macOS x86-64 and ARM64, and Windows x86-64, the targets of the Python wheels, whose CI matrix can be reused. At its first load the library is extracted to a temporary directory and loaded through SymbolLookup.libraryLookup. That makes one JAR of several megabytes, or one JAR per platform with a Maven classifier. Other platforms have no binary: Linux on s390x and ppc64le, common in the companies that run Java on IBM hardware.

Chicory ships one JAR for every platform the JVM runs on, with the module compiled to bytecode at build time. It needs no temporary file, which also suits restricted environments (a read-only /tmp, noexec mounts). Chicory’s documentation says the build-time compiler needs no reflection and so works more easily with native-image. The evaluator’s functions may exceed the JVM’s 64 KiB limit on a method’s bytecode. The compiler can then leave those functions to the interpreter (interpreterFallback), which is slower.

Both publish to Maven Central through the Central Portal. That requires a verified namespace (io.github.thkprado, verified through the GitHub account), GPG signatures, and sources and Javadoc JARs. The Java code is built by Maven, in crates/jlens-java/java/.

Performance

The point of jlens on the JVM is to be faster than jsonata-java while being more conformant. Panama keeps native speed and pays at the boundary. Chicory pays at the boundary (JSON text both ways) and in execution: its documentation lists being “the fastest runtime” among its non-goals. Neither cost is known for jlens, so the spike measures both against jsonata-java on the workload of benches/compare.

Decision

  • The package requires Java 25, and CI tests it on 25 and on each later release.
  • Panama is the only backend. Through Panama, a Document beats jsonata-java on its own objects by 2.6 to 70 times, and JSON text beats jsonata-java parsing the same text by 1.2 to 2.7 times (item 2). Concurrent evaluations scale to 150,000 to 205,000 a second on 16 hardware threads, or on 1,000 virtual threads, 1.8 to 2.5 times jsonata-java (item 7). A downcall costs 9 ns and an upcall 24 to 28 ns (item 6), so JNI has nothing to win.
  • One C API crate, crates/jlens-capi, not published to crates.io, holds the exports.
    • The lint. It declares the workspace’s lints itself, with unsafe_code = "deny". Only its exports module allows unsafe_code, for #[unsafe(no_mangle)], and a macro_rules! writes each export as one call to a safe function. A test fails if unsafe appears anywhere else in the crate’s Rust files, all of them, not only src/ (item 1).
    • Buffers. They are owned by Rust and known by handle; Java writes and reads them through the address Rust exposes. No Rust code dereferences a pointer it is given.
    • The tables of handles (buffers, expressions) are global, since a virtual thread can change carriers between two calls. Their locks are held only to find an entry, and each buffer has a lock of its own. A table locked across the work stopped all scaling in item 7.
    • Documents follow ADR 0014: the parsed JSON behind an Arc, converted once per OS thread into a thread-local cache.
    • mimalloc is the library’s allocator, as in the Python wheels. The large cases ran up to 2.7 times slower on Windows than on Linux, which points at Windows’ system allocator (item 2).
  • Inputs.
    • JSON text (a String, or UTF-8 byte[]) is the default, parsed only for the fields the expression reads (ADR 0016).
    • A Document is for an input evaluated many times.
    • Java objects (Map, List, strings, numbers, booleans, null) are accepted too, through a Source read with one upcall per level. It is documented as the slower way when an expression reads most of its input (item 2). Its Rust side takes the Python package’s levers, interned keys and one Sources per level, since the upcall is 2% of a level and Rust’s allocations most of the rest (item 6).
  • Results. They come back as JSON text, or as Java objects. Whether those objects are built by the result builder (ADR 0017) through upcalls, or decoded from the JSON text in Java, is measured when the package is built. $ on a large document is the case to watch: it is the one case where jsonata-java won in item 2, because it returns its input.
  • Distribution. One JAR carries the native libraries of the seven release targets, about 1 MB each compressed, about 7 MB in all (item 3). It extracts the right one at first use. Per-platform JARs with a Maven classifier can follow if the size matters to users. The install section documents --enable-native-access and the warning users see without it.
  • Limits. The native default depth of 50,000 holds on every kind of thread (item 4). A robustness test runs evaluations on a thread with a small -Xss.
  • Chicory is not shipped.
    • It fails the condition for a sole backend: even with -XX:-DontCompileHugeMethods, it stays 3.6 to 4.8 times below jsonata-java (item 7).
    • It needs that JVM flag, so it no longer spares users a launch flag.
    • Each instance holds about 5 MiB (item 6), and its default depth would be about 200 (item 4).
    • It can be weighed again if users ask for a JAR with no native code or for a platform without a binary, or if Chicory’s speed changes. The same C API crate compiles to wasm32-wasip1 unchanged (item 1). Items 3 to 6 say what such a backend needs: a module built with opt-level = "s", a depth limit near 200 on default stacks, and dropping an instance after an overflow.
  • JNI is not used.
  • The Java API is frozen with the other contracts outside Rust (ADR 0015), so the package starts after the API stability work of the roadmap, not before. (Superseded by the amendment below: the package ships before that work, in beta.)

Consequences

  • Java 21 users are not served. If demand appears, Panama cannot reach them. A Chicory backend (Java 11 and later) or JNI would.
  • What users get.
    • A JAR of about 7 MB, with native code for seven targets.
    • A launch flag, --enable-native-access: a later Java release will refuse native access without it.
    • No binary for Linux on s390x or ppc64le.
  • What the project takes on.
    • CI builds the library for each target and runs a Java test suite on each.
    • The release checklist gains a Maven Central step, which, like cargo publish, cannot be undone.
    • The book gains a Java chapter beside the WebAssembly and Python ones.
  • Beyond Java. The C API could later serve other languages that call C (.NET, Go, Ruby). That is not a goal of this ADR, but the crate is kept free of Java specifics with that in mind.
  • Two costs in jlens-core showed up. They are for the core, outside this ADR, and they apply to the Python package too.
    • On a Document of 100,000 items, the path items[0] builds the whole sequence of items before taking the first: 0.9 to 2.4 ms.
    • The Sink allocates once for each key, each string and each nested source (keys are interned: see the amendment).
  • The spike’s code is kept outside the repository. Its results are below.

The spike

Run on 2026-10-25, before this ADR was accepted, on Windows x86-64 and Linux x86-64 (WSL 2), with Java 25 and the release build:

  1. A C API crate with one export, a crate-level exception for no_mangle, and a check that an unsafe block in the crate is still refused. Buffers by handle, read from Java through MemorySegment and through Chicory’s Memory.
  2. Microseconds per evaluation, best of five, on the documents of ADR 0014’s table (1,000 and 100,000 items). Columns: Panama on JSON text; Panama with a Source over Map/List through upcalls; Panama on a Document; Chicory (build-time compiler) on JSON text; Chicory on a Document; jsonata-java.
  3. How many of jlens’s functions the build-time compiler leaves to the interpreter, and the size of the compiled JAR.
  4. The depth at which Chicory overflows the default JVM stack, with and without an audit, to set its DEFAULT_MAX_DEPTH. Also: does the instance stay usable after a StackOverflowError?
  5. Whether wasm32-wasip1 links with --stack-first, and whether a timeout fires through Chicory’s WASI clock.
  6. The cost of a new Chicory instance, and of a Panama upcall per level read, to size the pool and the Source.
  7. Throughput with virtual threads: many concurrent evaluations of one Expression, Panama (pinned carriers) against a Chicory pool, and the warning Java 25 prints without --enable-native-access.

Results

Item 1 (2026-10-25; Rust 1.99.1, Chicory 1.7.5 with its interpreter; Windows x86-64 with Temurin 25.0.4, and Linux x86-64 (Ubuntu 26.04 on WSL 2) with Ubuntu’s OpenJDK 25.0.4, with the same results on both). The crate had five exports: jlens_buffer_new, jlens_buffer_address, jlens_buffer_len, jlens_buffer_free, and jlens_evaluate, which takes the handles of an expression and an input in JSON and returns a buffer with {"result": ...} or {"error": {"code", "position", "message"}}.

  • The lint. With the crate’s own lints (unsafe_code = "deny") and #[allow(unsafe_code)] on the exports module, cargo clippy --all-targets reports no warning.
    • An unsafe {} block elsewhere in the crate fails (error: usage of an unsafe block).
    • The same block inside the exports module compiles, as expected.
    • The source test catches the second case. It must scan every Rust file of the crate, not only src/: a #[path] module outside src/ escaped a scan of src/ alone.
  • Buffers by handle. The table is global behind a Mutex, not thread-local, since a virtual thread can change carriers between two calls. A buffer is a Vec<u8> that is never resized, so its address stays valid until it is freed. The address is handed out with expose_provenance, since foreign code writes through it. The crate has no other unsafe.
  • Panama. Java wrote the inputs with MemorySegment.ofAddress(address).reinterpret(len) and read the results the same way, through invokeExact downcalls. The results were right, including é, ☕ and 😀 in both directions, and an error envelope with S0207. 1,000 virtual threads each made their own evaluation, sharing the table, with no wrong result. Without --enable-native-access Java 25 printed four lines, starting with WARNING: A restricted method in java.lang.foreign.SymbolLookup has been called, and ran on.
  • Chicory. The same crate built for wasm32-wasip1 with no change. The module exports memory and the five functions, with no _initialize. It imports six WASI functions from Rust’s standard library: random_get, environ_get, environ_sizes_get, clock_time_get, fd_write and proc_exit. Chicory’s WasiPreview1 provides them. Through Memory.write and readBytes, the same cases gave the same results, $millis() read the clock through WASI, and 1,000 evaluations in a row gave no wrong result.
  • Sizes, in a release build with lto, unstripped and not tuned: 2.2 MB for the Windows DLL, 2.6 MB for the Linux .so, 1.7 MB for the WebAssembly module.

Item 2 (2026-10-25, the same machine and versions; jsonata-java 0.9.10; the system allocator, not mimalloc).

  • Method. One thread, one second of warm-up, then the best of five runs of at least 0.3 s each. The document has n items with five fields each: id, name ("item 17"), price (0 to 99.99), tags (two strings) and stock (an object with two fields). That makes 97 KB of JSON for 1,000 items and 10.1 MB for 100,000.
  • What each column includes.
    • Every jlens column returns its result as JSON text, decoded into a Java String. jsonata-java returns Java objects.
    • “JSON text” starts from a Java String: it encodes it in UTF-8, copies it into a Rust buffer, and parses only the fields the expression reads (ADR 0016).
    • “Source” reads the Maps and Lists that jsonata-java’s own parser (Json.parseJson) built. It makes one upcall per level, and Java encodes the level into a Rust buffer.
    • “Document” is parsed once, before the timing.
    • “jsonata-java, parsing” parses the String and then evaluates.
  • Chicory runs the module that its build-time compiler turned into JVM classes. Every function compiled: none was left to the interpreter. The generated files take 2.4 MB, 1.7 MB of it in one class. With HotSpot’s defaults, its methods exceed the 8,000 bytes of bytecode above which HotSpot does not JIT-compile (DontCompileHugeMethods), so they run in the JVM’s own interpreter. The table gives Chicory with -XX:-DontCompileHugeMethods. Without that flag, JSON text takes 13 to 25 ms on 1,000 items (4 to 5.5 times longer, but for $) and 1.8 to 2.0 s on 100,000, and a Document up to 2.5 times longer (2.9 on Linux).

Microseconds per evaluation on Windows x86-64:

ExpressionPanama, JSON textPanama, SourcePanama, DocumentChicory, JSON textChicory, Documentjsonata-javajsonata-java, parsing
1,000 items (97 KB)
items[0].name5291204.83,5354278759
$count(items)2771131.22,3915.980756
$sum(items.price)4821,490344,106606146820
items[price > 98].id6331,6011276,0951,0853241,004
$3,2554,5211,85817,7139,751145803
100,000 items (10.1 MB)
items[0].name63,18318,3912,362354,7613,70833,59476,769
$sum(items.price)62,936217,78612,844410,67139,21351,67292,613
$464,131641,011264,8271,992,5631,008,85966,10886,128

Linux x86-64 (WSL 2) gives the same picture.

  • Panama takes 2 to 43% less time there, and 2.7 times less on items[0].name over the 100,000-item Document (885 µs against 2,362).
  • Chicory without the flag takes within 7% of the Windows times. With it, it mostly takes within 17% of them, but $sum(items.price) on a Document of 1,000 items takes 313 µs against 606.
  • jsonata-java takes within 12% of the Windows times. The exception is parsing and summing the large document, which takes 1.9 times longer.
  • The difference points at Windows’ system allocator, which the native library would replace with mimalloc, as the Python wheels do (ADR 0014, amendment).

What this says:

  • Panama on a Document beats jsonata-java on its own Java objects in every case but $. On 1,000 items it is 16 times faster on items[0].name, about 70 times on $count(items), 4.3 times on $sum(items.price) and 2.6 times on the filter. On 100,000 items it is 14 times faster on items[0].name and 4 times on $sum(items.price).
  • $ is not a fair comparison. jsonata-java returns its input object, while jlens serializes the whole document and Java decodes it. A result written straight into Java objects (ADR 0017’s builder, through upcalls) is the fair comparison, and it is not measured yet.
  • Panama on JSON text beats jsonata-java when both start from a String.
    • On 1,000 items it is 1.4 to 2.7 times faster.
    • On 100,000 items, items[0].name is 1.2 times faster and $sum(items.price) 1.5 times.
    • Only $, which returns the whole document, is slower.
  • A Source over Java objects only pays when the expression reads little.
    • items[0].name and $count(items) take 120 and 113 µs, against 529 and 277 µs from JSON text.
    • Reading every item costs about 1.5 µs per level (one upcall, plus encoding in Java). So $sum(items.price) takes 3 times longer than from JSON text, and 10 times longer than jsonata-java. Python’s level reading was close (1,770 µs for the same case).
    • The package would therefore take Java objects as an input, but neither as its default nor as its fast path.
  • Chicory fails the decision’s condition for a sole backend.
    • JSON text, the common case, is 3 to 6 times slower than jsonata-java parsing, even with the flag (22 times for $).
    • A Document is faster than jsonata-java when the expression reads little ($count, items[0].name). When it reads every item, it is 3 to 4 times slower on 1,000 items, and faster on 100,000 ($sum(items.price): 39 ms against 52).
    • Chicory also needs a JVM flag to reach these numbers, which removes its one advantage over Panama: no launch flag.
  • The path items[0] on a Document of 100,000 items costs 0.9 to 2.4 ms, as it did in Python (2,480 µs, ADR 0014). The core builds the whole sequence of items before taking the first. That belongs to jlens-core, outside this ADR.

The full tables, Linux included, are in the spike’s bench/results-*.md.

Item 3 (2026-10-25, the same module and versions as item 2).

  • No function is left to the interpreter. The build passes with interpreterFallback=FAIL. The module gives 2,963 methods and 1.47 MB of bytecode. The largest method takes 25,776 bytes, 39% of the JVM’s limit of 65,535.

  • 29 methods exceed HotSpot’s 8,000-byte limit for JIT compilation, and they are hot paths. Without -XX:-DontCompileHugeMethods they run in the JVM’s interpreter, which explains item 2’s slow Chicory columns. They include:

    • Evaluator::path, Evaluator::group and Evaluator::apply_inner;
    • the pruned parse’s CutSeed and serde_json’s f64_from_parts;
    • the parser (Parser::expression, led_step) and the Processor;
    • ten of jlens-regress’s backtracking functions, and its parser;
    • $replace, $formatNumber and the date-time parser.
  • Built with opt-level = "s", as the WebAssembly package is, the module gives 4,718 smaller methods: 16 exceed 8,000 bytes, and the largest takes 20,725. Without the flag, JSON text then takes 2.9 to 6.3 ms on 1,000 items instead of 13 to 25 ms, about what opt-level = 3 takes with the flag ($ stays near 20 ms either way). A Document still needs the flag: $sum(items.price) takes 1,087 µs without it, 386 µs with it (one run of each, Windows). The verdict of item 2 stands.

  • Sizes, as a JAR compresses them (deflate):

    PartRawCompressed
    Chicory: the generated classes and module metadata, opt-level = 32.39 MB0.78 MB
    Chicory: the same, opt-level = "s"2.22 MB0.69 MB
    Chicory’s runtime, wasm, wasi and log JARs0.43 MB
    Panama: the Windows DLL2.28 MB0.93 MB
    Panama: the Linux .so, stripped2.40 MB0.97 MB
  • What a user downloads.

    • With Chicory: one JAR of about 1.2 MB, the same everywhere, with its runtime.
    • With Panama: about 1 MB per platform, so about 7 MB for one JAR with the seven targets, or about 1 MB per platform JAR with a Maven classifier.
    • Both are about the size of a Python wheel (1.1 to 1.3 MB, ADR 0014).

Item 4 (2026-10-25, the same versions; the module linked with a 4 MiB stack, as jlens-wasm is).

  • Method. The shapes are those of the WebAssembly guide’s depth table, plus a recursion through $map, each with and without a full audit. Each probe runs a fresh instance with a given depth limit and records whether the evaluation stops with D1011 or overflows the JVM’s stack (StackOverflowError).
    • The JVM’s own stack is used: 1 MiB for the main thread and for a new platform thread, and its default for virtual threads.
    • In one JVM, three passes search every shape: the first runs cold, the later ones once the JIT has compiled more of the module. Each shape then runs 20 times at the smallest depth found.
    • Separately, each shape runs alone in a new JVM.
  • The worst case comes while the JIT is warming up, neither cold nor warm. The smallest depth that fits was 273 on Windows and 263 on Linux, for the order-by ([$n, $n]^($f($n - 1))). It was the same within 4% on virtual threads, on platform threads and with -XX:-DontCompileHugeMethods.
    • A shape that runs alone in a new JVM fits more: 494 to 606 for the order-by and the $map recursion.
    • Once warm, most shapes fit 600 to 1,500.
    • At a limit of 250, every shape stopped with D1011 in a new JVM, on Windows and Linux, on the main thread and on a virtual thread.
  • So on the JVM’s default stacks, Chicory needs a default depth near 200, against WebAssembly’s 500 in V8 and 50,000 natively. 200 leaves the margin that 500 leaves against V8’s 670. DEFAULT_MAX_DEPTH is chosen by target_arch alone, and V8 and Chicory both run wasm32, so the C API would pass its own default in Options.
  • Or the package evaluates on threads of its own, with larger stacks. On a platform thread with an 8 MiB stack, the worst case fits 2,468 in a new JVM: the order-by, audited.
    • Once the JIT is warm, no shape overflows at all: the module’s own guard, which watches its 4 MiB stack, stops every evaluation with D1011 first.
    • The cost is a handoff to that pool for each evaluation, from a virtual thread too. Items 6 and 7 can measure it.
  • After a StackOverflowError, the instance still answers, but it is damaged.
    • 1 + 1 and recursions within their limit still work.
    • The trap skips the code that restores the module’s stack pointer, the __stack_pointer global. Each overflow left 420 to 715 KB of the 4 MiB stack in use, so a few overflows use it up.
    • What the evaluation held on the heap is lost, and an overflow in the middle of the allocator would leave it inconsistent.
    • The host can save the pointer before each call and restore it after an overflow; the spike did, and the stack was whole again. That does not repair the heap, so the package drops the instance instead, and its pool makes a new one.
  • The __stack_pointer at rest is 4,194,304, the size of the stack. So the stack sits at the start of linear memory and grows down to address 0, as --stack-first places it and as stack::exhausted assumes. That answers the first half of item 5.
  • Panama stops every shape, audited or not, at the default depth of 50,000 with D1011. That holds on the main thread, on a new platform thread and on a virtual thread, whose carrier’s stack stacker extends.

Item 5 (2026-10-25, the same versions; Chicory with HotSpot’s default flags).

  • --stack-first: yes, as item 4 showed. The __stack_pointer at rest equals the stack’s size.
  • The workload is $sum([1..200].($sum([1..100000].($ * 2)))), about 20 million steps. It takes 32.0 s on Chicory and 2.3 s through Panama on Windows, and 29.1 s and 1.9 s on Linux.
  • The timeout fires through the WASI clock. On Chicory, Instant::now reads WASI’s clock_time_get, which WasiPreview1 provides.
    • Timeouts of 10, 100 and 1,000 ms stopped the evaluation with D1012 every time, 5 runs each.
    • On Chicory the error came at most 5.1 ms late on Windows and 9.2 ms late on Linux. Through Panama it came at most 1.4 ms and 0.6 ms late.
    • The instance answered 1 + 1 afterwards: D1012 is an ordinary error, not a trap.
  • Reading the clock costs nothing measurable. The clock is read every 256 steps (ADR 0018). Against no timeout at all, a timeout of an hour changed the time by -0.6% to +0.1% on Chicory and by +0.6% to +1.8% through Panama, within the noise of a single run.

Item 6 (2026-10-25, the same versions; Windows, then Linux. On Linux the classes were copied off WSL’s /mnt mount first: read from there, they made the first evaluation 28 times slower and each new instance 2.7 times slower.)

  • A Chicory instance, warm, takes 0.55 to 0.58 ms to create, and 0.64 to 0.67 ms with a first 1 + 1. That is 13 to 90 times one of item 2’s small evaluations on a Chicory Document (5.9 to 42 µs). So a pool makes its instances ahead of time, and replacing one after an overflow (item 4) costs under a millisecond.
  • The first one in a JVM costs more:
    • loading the module (JlensModule.load()): 108 to 140 ms;
    • creating the first instance: 49 to 64 ms;
    • its first evaluation: 46 to 51 ms. That is about 0.2 s of start-up, which a pool can pay when the application starts.
  • Each idle instance holds 4.8 MiB of the Java heap, its linear memory: 71 pages of 64 KiB, the 4 MiB stack of item 4 and the module’s data. Parsing a Document of 1,000 items grows it to 86 pages, 5.4 MiB.
    • A pool therefore costs about 5 MiB per instance, before its documents: 16 instances take 80 MiB.
    • A smaller stack would save most of that. On the JVM’s default stacks, only 0.4 to 0.7 MB of it was in use when the JVM’s own stack overflowed (item 4). The stack size is therefore a choice between memory and the depth that 8 MiB threads allow.
  • Panama’s calls are cheap:
    • a downcall that does nothing: 9 ns;
    • an upcall that does nothing, made from Rust: 24 to 28 ns.
  • Reading one level through the reader is mostly Rust’s work, not the boundary’s.
    • The reader’s Java work for one item of item 2’s document takes 223 to 300 ns: 137 to 179 ns to encode its five fields (79 bytes), and 75 to 93 ns for the three downcalls that copy it into a Rust buffer. That includes the upcall.
    • Item 2’s $sum(items.price) read 1,000 such items through the Source, at about 1.45 µs per item on Windows and 1.1 µs on Linux, the evaluation itself deducted (its Document time).
    • By subtraction, 0.9 to 1.2 µs of each item is spent in Rust: decoding the level and the Sink’s allocations. Each key and string is an Rc<str>, and each nested array or object is a boxed source of its own.
    • The upcall is 2% of a level. The Python package’s levers apply: keys interned for the expression, the arrays and objects of a level written as members of one Sources, and mimalloc. They are not measured here.

Item 7 (2026-10-25, the same versions; 16 hardware threads, a Ryzen 7 3700X).

  • Method. One compiled $sum(items.price) is evaluated on 9.5 KB of JSON text (100 items of item 2’s document), over and over.
    • The workers are 1 to 16 platform threads, or 1,000 virtual threads.
    • The rate is counted over 3 s, after 2 s of warm-up.
    • Chicory serves the workers from a pool of 16 instances, one per hardware thread. A virtual thread waiting for an instance unmounts from its carrier.
    • jsonata-java parses the text and evaluates, with one Jsonata object per thread.
  • A first run did not scale at all. Panama gave 20,383 evaluations per second on one thread and 18,758 on 16. The spike’s buffer table held its global lock while evaluate_json parsed the input. With one lock per buffer, and the table’s lock held only to find a buffer, it scales as below. The package’s C API must not serialize work behind its handle tables.

Evaluations per second (and the speed-up over one thread):

Engine1 thread4 threads16 threads1,000 virtual threads
Windows
Panama19,79571,596 (3.6×)150,036 (7.6×)149,892 (7.6×)
Chicory4811,681 (3.5×)3,236 (6.7×)3,126 (6.5×)
Chicory, -XX:-DontCompileHugeMethods2,47610,494 (4.2×)22,996 (9.3×)22,663 (9.2×)
jsonata-java11,92245,023 (3.8×)85,472 (7.2×)86,319 (7.2×)
Linux (WSL 2)
Panama22,50582,500 (3.7×)204,750 (9.1×)204,165 (9.1×)
Chicory4541,536 (3.4×)3,125 (6.9×)2,974 (6.6×)
Chicory, -XX:-DontCompileHugeMethods2,5449,600 (3.8×)22,831 (9.0×)20,880 (8.2×)
jsonata-java11,54141,580 (3.6×)82,595 (7.2×)83,387 (7.2×)
  • Pinning costs nothing here. 1,000 virtual threads calling Panama give the rate of 16 platform threads: the work is CPU-bound and each call is short (about 50 µs), so the 16 carriers stay busy. A host function that blocks while its virtual thread is pinned would hold a carrier for that time; that is not measured.
  • Panama beats jsonata-java at every thread count. It is 1.7 to 2.0 times faster on one thread, 1.8 times on 16 threads on Windows, and 2.5 times on Linux, where it scales further (9.1×).
  • A pool of 16 Chicory instances serves 1,000 virtual threads at the rate of 16 platform threads. Chicory stays 3.6 to 4.8 times below jsonata-java even with the flag, and 25 to 26 times below without it.
  • The warning Java 25 prints without --enable-native-access is item 1’s: four lines on standard error, once per module.

Amendment: before the API work (2026-10-25)

Context

The decision tied the package to the API stability work (ADR 0015) of the roadmap. That work is deferred until applications built on jlens have used jlens, with no date, so the package would wait with it. The Python and WebAssembly packages did not wait: they shipped in beta, and the API work covers them when it comes.

Decision

  1. The package is roadmap 0.25, before the API work. It ships in beta, with the workspace’s 0.x versions, as the Python package does. Its API may change until 1.0, and ADR 0015 adds it to the contracts outside Rust that it freezes.
  2. Results as Java objects are part of the package, not left for later. How they are built, through the result builder (ADR 0017) with upcalls or by decoding the JSON text in Java, is measured in 0.25 #5.

Consequences

  • When the API work breaks the API, the Java package changes with the Python and WebAssembly ones. jlens-capi is not published, so only the Java API’s users see the change.
  • The package becomes one more use of the contracts outside Rust that ADR 0015 decides from.
  • Every release from 0.25 on publishes to Maven Central too: one more step in the checklist, and one more channel to check.

Amendment: what the Sink allocates (0.24)

Context

The Consequences and the results of spike item 6 say that the Sink allocates once for each key. It does not: keys are interned. An evaluation keeps a table of the keys its sources have written, and allocates an Rc<str> for each distinct key once (up to 1,024 of them); after that a key costs a hash and a lookup in the table, and no allocation. Roadmap 0.24 #3 profiled a level read through the Sink (performance).

Decision

  1. The spike’s results stand corrected. The Sink allocates once for each string, each array or object written (the lazy value), and each source written with Sink::array or Sink::object, which Sink::array_of and Sink::object_of avoid (ADR 0010, amended). A key is allocated once per evaluation. The spike’s reader wrote each nested value with its own source, so part of the 0.9 to 1.2 µs per item it found in Rust was those boxes.
  2. The levers decided above stand. The Java package’s reader writes the arrays and objects of a level as members of one Sources, and it also gives the Sink the size of each level (Sink::reserve), which since 0.24 makes room for the level’s keys too.

Consequences

  • Most of what remains of a level is allocating and freeing a lazy value for each array or object, about 99% of the time of 10,000 objects that the expression does not read. mimalloc, already decided for the library, is the lever for it; the Sink’s own work is a few percent.
  • An index into a long array reads the array’s whole level, so items[0] costs as much as writing every item. A reader that could write one item alone, as Source::read_field writes one field, would avoid it: roadmap 0.24 #4 measures it.

Results: the C API (0.25)

Options and documents (0.25 #2)

  • Options are an object of the C API, made once from JSON text with the names of the WebAssembly package’s options (timeout in milliseconds, maxDepth, maxSteps, maxStringLength, maxArrayLength, maxResultSize, now, seed) and passed to each evaluation by handle, 0 for the defaults. An evaluation then reads no options: an application sets them once and evaluates many times. Options that are not in their form fail with U2005, an unknown name included, so that a misspelt limit does not pass unnoticed.
  • Documents are JSON text behind an Arc, converted once per OS thread, as decided. A thread drops its conversion of a freed document the next time it makes, frees or evaluates against a document; a carrier thread that never does keeps it until it exits. (0.25 #3: at its next call of any export; see below.)
  • The reads come back as the JSON of Expression::reads, and their union is made from a JSON array of them, as union_reads does in Python. A document is pruned to the input of either.

mimalloc (0.25 #2)

jlens_evaluate on JSON text, called through the exports from Rust on the maintainer’s Windows machine, with the spike’s documents and expressions. Each evaluation copies the text into a buffer first, as the Java package will. Microseconds; the best of two alternated runs, each the best of five runs of 0.3 s after a second of warm-up.

ItemsExpressionSystem allocatormimallocChange
1,000items[0].name465338−27%
1,000$count(items)253220−13%
1,000$sum(items.price)459362−21%
1,000items[price > 98].id613503−18%
1,000$2,9761,953−34%
100,000items[0].name56,89237,237−35%
100,000$sum(items.price)58,50740,012−32%
100,000$452,303225,514−50%

On a Document, where nothing is parsed, the same cases take 7 to 53% less: $sum(items.price) over 100,000 items 5,646 µs against 12,021, and $ 128,301 against 252,318. mimalloc is the library’s global allocator, with local_dynamic_tls, as in the Python package.

Freed documents (0.25 #3)

A thread now drops its conversions of freed documents at its next call of any export, a buffer’s included, not only of the documents’ exports. A count of the documents dropped, bumped when a document’s text is dropped (its last Arc, so after an evaluation that still held it returns), tells each export whether the thread has conversions to sweep: one atomic load per call when nothing was freed. A conversion is then kept only by a thread that never calls jlens again, at most one per idle carrier thread. Releasing it at once on every thread was set aside: a jlens_core::Document is not Send, an Arc inside it would slow down every evaluation, and an export that releases the calling thread’s conversions would not reach the carriers of virtual threads.

items[0].name on a Document of 1,000 items, through the exports from Rust: 616 to 623 ns before, 603 to 609 ns after. The lookup of a conversion no longer sweeps the cache on every evaluation, which pays for the load.

The comparison harness (0.25 #4)

cargo xtask java-compare runs benches/compare/java (its README says how): the spike’s documents, the workload of benches/cases.json, and the spike’s throughput on platform and virtual threads, with each engine’s result checked against jlens’s first. Maven Central, searched again, has a JVM implementation the spike did not measure: jsonata-jvm-compiler 1.0.7, which translates an expression to Java and compiles it with javac at run time, over Jackson 2. The harness measures it with jsonata-java 0.9.10 and JSONata4Java 3.0.0; the README lists the packages left out and why. Every result agreed with jlens’s, except two cases JSONata4Java rejects ($formatNumber on a path’s value, the transform operator).

Measured on Windows x86-64, Java 25.0.4, the machine of the spike:

  • The harness reproduces the spike. jsonata-java, unchanged since, takes within 4% of the spike’s times on its objects of 100,000 items and on parsing 1,000, 9% longer on parsing 100,000 for items[0].name, and 5 to 11% longer on its objects of 1,000 items (83 against 78 µs on items[0].name). On threads it gives 12,030 evaluations per second on one and 85,981 on 16, against 11,922 and 85,472.
  • jlens is faster than in the spike, as #2 measured: on JSON text of 1,000 items it takes 232 to 529 µs where the spike took 277 to 633, and 2,041 µs on $ (3,255); on threads, 25,350 evaluations per second on one, 224,252 on 16 and 217,297 on 1,000 virtual threads (19,795, 150,036, 149,892). A Document now costs the same whatever its size: items[0].name takes 0.88 µs on 1,000 items and 0.87 on 100,000, where the spike’s took 4.8 µs and 2,362.
  • jsonata-jvm-compiler is the one to beat on an input converted once. On a Jackson tree it takes 0.03 µs on path (jlens’s Document 0.54), 8.7 against 27 µs on $sum(items.price) over 1,000 items, and 1.8 (number formatting) to 26 times (recursion) less than jlens on every case of cases.json but one: on ($i := 0; items[$i].code) it takes 43 µs against 1.2. Its expression is a Java class, which the JIT compiles with the application.
  • From JSON text, jlens is the fastest where the parsing is the cost. It reads only the fields an expression reads (ADR 0016), and the others parse the whole text with Jackson or their own parser: on path it takes 32 µs against 99 to 158, and 366 against 686 to 786 µs on items[0].name over 1,000 items. Where the evaluation is the cost, jsonata-jvm-compiler wins: 138 against 910 µs on recursion, 169 against 400 on sort + map. On 100,000 items jlens takes 40 to 42 ms against 70 to 108 for the others, but on $.
  • On threads, jlens leads all three: 224,252 evaluations per second on 16 threads, against 121,630 for jsonata-jvm-compiler, 85,981 for jsonata-java and 79,938 for JSONata4Java.
  • $ is still the case to watch. jsonata-java and the two Jackson engines return their input; jlens writes the whole document as JSON text (1,092 µs on 1,000 items, 128 ms on 100,000). That is #5’s to measure.

Results as Java objects (0.25 #5)

Three ways of building a result as Java objects were measured with #4’s harness, each against a Document, on the maintainer’s Windows machine:

  • Upcalls: the result builder (ADR 0017) calls one Java function for each value, key and end of an array or object, and Java builds the objects on a stack of its own.
  • JSON text decoded in Java: the C API writes JSON text, as before, and Jackson’s readValue(text, Object.class) decodes it, a well-optimized decoder the package would not depend on, so the upper bound of this way.
  • Values: the result builder writes a tagged binary encoding into the reply, which Java decodes with no parser and no upcall: a tag byte for each value, lengths and numbers little-endian, and each distinct key once, then by its index, so that Java makes one String per key for the whole result.

Microseconds per evaluation, the best of five runs of 0.3 s after a second of warm-up:

ItemsExpressionJSON text, not decodedValuesUpcallsJSON text + Jackson
1,000items[0].name0.850.840.950.97
1,000items[price > 98].id116119121117
1,000$1,1344982,6441,878
100,000$sum(items.price)5,8635,7155,7975,805
100,000$132,68556,450282,832206,302

On benches/cases.json the values are within the noise of JSON text on small results, and faster on large ones: object constructor 126 µs against 163 (214 with Jackson), transform 485 against 570 (677).

  • Values are kept: they are the fastest, or within the noise of the fastest, on every case, and on large results faster even than JSON text that is not decoded at all, since a value is written with no formatting and a key once. Upcalls cost about 25 ns each and one is made for each value and key, so they are the slowest on large results; decoding JSON text pays for writing it and parsing it again.
  • The C API takes the format as an argument of jlens_evaluate and jlens_evaluate_document: 0 for JSON text, 1 for values, whose reply starts with byte 4. The encoding is documented in jlens-capi’s values module.
  • The Java types: objects are LinkedHashMaps, their fields in order; arrays ArrayLists; integral numbers in a long’s range Longs, the others Doubles. A BigDecimal was set aside: jlens’s numbers are f64s, so it would be slower and suggest a precision the value does not have, and Double.toString already prints the shortest decimal that reads back the same. The Python package’s bound of 10^21 for an int does not fit a long; past 2^63 a number is a Double. Undefined and null are both null, as in Python; evaluateJson tells them apart. The objects are made for each evaluation, and the caller may modify them.
  • $ on a Document now takes 502 µs on 1,000 items, against 154 for jsonata-java, and 56.6 ms on 100,000, against 67.1 ms. The Jackson engines take 0.02 to 0.08 µs because they return their input. jlens can do the same only when its input is Java objects, which #6 adds: a result that is the input unchanged is then returned as is.

Java objects as input (0.25 #6)

Expression.evaluate(Object) reads maps, lists, strings, numbers, booleans and null one level at a time, as the evaluation reaches them, through one upcall per level (source.rs in jlens-capi):

  • One Sources per evaluation. Java numbers each map and list as it meets them, and every array or object of the input is a member of one Sources in Rust, known by its number: a level costs Rust no allocation of its own, the levers of the spike’s item 6 and of the amendment above. Each level written gives its size to Sink::reserve.
  • One field or one item alone. The reader has four operations: a whole level, one field of a map (read_field; Java gets the key’s UTF-8 bytes from Rust’s memory), the length of a list and one of its items (length, read_item), so a path or an index reads what it picks. A list that is not RandomAccess (a LinkedList) tells no length, and is read whole. A reader may also decline a field or an item; the level is then read whole.
  • One buffer. Java encodes a level into a byte array and copies it into one C API buffer per evaluation, made larger when a level does not fit: a level costs one upcall and no downcall.
  • The input returned as itself. A map or list the result holds unchanged comes back as the object itself, through Builder::input (ADR 0017, amended): $ returns the input, as jsonata-java does, and a filter returns a new list of the input’s maps.
  • Failures. A type the reader does not read (a Date, an int[]), a key that is not a string, or a map or list inside itself fails with U1004 when the evaluation reads it, with a message that names it; an exception never crosses the upcall. A cycle is detected through the chain of levels a value was read from, as json.dumps does in Python. Input nested deeper than a result may be fails with U1001 when it is written; returned as itself, it is not written. On threads of 128 KiB to 1 MiB, inputs nested 100,000 levels deep stop with U1001 or give their result, with the upcalls made from the stack segments jlens grows into (jlens_core::stack): the JVM runs them there.

Microseconds per evaluation with #4’s harness on the maintainer’s Windows machine, Java 25.0.4; “objects” reads the maps and lists that Jackson’s readValue(json, Object.class) built, and the spike’s “Source” column (above) is repeated for comparison:

ItemsExpressionSpike, SourceObjectsDocumentjsonata-javajsonata-jvm-compiler
1,000items[0].name1202.520.8683.70.03
1,000($i := 0; items[$i].name)2.921.221490.65
1,000$count(items)1131.940.8589.00.03
1,000$sum(items.price)1,49032727.51528.0
1,000items[price > 98].id1,60139811732915.4
1,000$4,5210.804831570.03
100,000items[0].name18,3912.590.8933,6850.04
100,000($i := 0; items[$i].name)2.901.2340,436217
100,000$sum(items.price)217,78648,2415,73655,5514,142
100,000$641,0110.8054,32966,8890.02
  • What reads little costs the same whatever the size: items[0].name takes 2.5 µs on 1,000 or 100,000 items, against 120 µs and 18 ms in the spike, which read each level whole, and 34 ms for jsonata-java. $ takes 0.8 µs, the cost of an evaluation that returns its input.
  • What reads everything costs 0.3 to 0.5 µs a level, against the spike’s 1.5: $sum(items.price) takes 327 µs on 1,000 items, 4.5 times less than in the spike but twice jsonata-java’s 152 µs, and 48 ms on 100,000, ahead of its 56 ms. A Document stays the fast way for an input evaluated many times, or read whole.

Host functions (0.25 #7)

Host functions written in Java follow ADR 0006 and ADR 0011, as the Python and WebAssembly packages do, through one more upcall (host.rs in jlens-capi):

  • Bindings, made once. Variables and host functions are bound by a Bindings object, built by a builder and immutable, that holds a native object: its variables are written to Rust when it is built, so an evaluation does not convert them again, and one Bindings serves any number of evaluations, of any expression, on any thread. Every evaluate method takes one. There is no registerFunction: it would make an Expression mutable, shared between threads, and a Bindings built once plays its part. A name holds a value or a function, and a name given with its $ is taken without it, as registerFunction does in Python and WebAssembly.
  • HostFunction, a functional interface, Object call(List<Object> arguments), bound with an arity or a signature: a Java lambda has no arity Java can read, where Python reads the parameters of a function. It throws no checked exception, so that evaluate declares none. A host function does not receive the context of its call (HostFunction::without_input), as in Python: a signature with - passes it as an argument.
  • Values both ways. The arguments reach Java as values (0.25 #5), with two more tags: an undefined argument, and a function with its arity, which Java turns into a JsonataFunction. The names Function and Callable would clash with java.util.function.Function and java.util.concurrent.Callable. Java writes its results, the arguments of the functions it calls and the variables in the same encoding, which Rust decodes with no parser; a value nested more than 1,000 levels deep fails with U1001, since Rust would drop it by recursion. Java’s writer walks with its own stack, as Values does.
  • Calling a function received. The core’s Callable borrows the call (ADR 0011). Each host call is a frame of a scoped thread-local in Rust, numbered, and Java’s JsonataFunction calls jlens_call with that number. A virtual thread is pinned during the downcall, so the upcall, and the downcall it makes, run on the same carrier. A call after the host function returned, or from another thread, fails with U1005: Java checks it first, Rust again.
  • Exceptions thrown again, unchanged. An exception a host function throws is kept by the evaluation, in Java, under a number that the error carries back through Rust (hostException in the envelope), and evaluate throws the same object again. An error of a function a host function called gets a number from Rust, kept while a host call runs on the thread; when the host function lets it through, Java replies with the number, and the error keeps its code and position, as failures does in Python. A CompletionStage or a Future as a result fails with U1002, as a promise or a coroutine does.

Host functions run while their virtual thread is pinned: one that blocks holds its carrier for that time, which the Java chapter says (0.25 #13).

Measured on the maintainer’s Windows machine, Java 25.0.4. The evaluations that take no bindings did not change: #4’s harness on 1,000 items, 02a69e1 against this item, gave the same times within the noise, on a Document (items[0].name 0.89 µs before, 0.84 to 0.88 after) and on Java objects (2.63 before, 2.52 to 2.56 after). Microseconds per evaluation with no input, the best of five runs of 0.3 s:

ExpressionBindingsµs
1 + 2none0.48
$a + $btwo variables0.67
$a + $btwo variables, one function0.78
$a + $btwo variables, four functions1.10
$a + $btwo variables, sixteen functions2.17
$add(1, 2)two variables, four functions1.99
$add(1, 2), signature <nn:n>the same2.15
$apply(function($x) { $x + 1 }, 1)the same2.93
$sum([1..100].$add($, 1))the same93.7
$sum([1..100].($ + 1))the same12.7
  • A host call costs about 0.8 µs: an upcall, the arguments written and read as values both ways, and the result. Calling back a function it received costs as much again.
  • Bound functions cost about 0.09 µs each per evaluation, called or not: the core binds every host function in the evaluation’s root frame before it starts (eval.rs), a cost the Rust, Python and WebAssembly packages share. The Java side’s own cost, the evaluation’s Host in a ScopedValue, is about 0.02 µs. Looking a host function up in the bindings when a name is not found, instead of binding them all, would remove it; that is a change to the core, left for its own item. 0.25 #9 made it (ADR 0006, amended, and below).

Host functions looked up on a miss (0.25 #9)

The core looks a host function up in the bindings when no frame holds its name, and keeps it in the root frame, instead of binding every one before the evaluation (ADR 0006, amended). Measured on the maintainer’s Windows machine, Java 25.0.4, microseconds per evaluation with no input, the best of five runs of 0.3 s, the JAR of 4701ddc against this item’s, both run from the class path by the same program (which is why the times are above those of #7’s table):

ExpressionFunctions boundBefore µsAfter µs
1 + 2none0.790.78
$a + $bnone0.960.96
$a + $bone1.101.03
$a + $bfour1.371.03
$a + $bsixteen2.501.04
$add(1, 2)four2.212.05
$add(1, 2)sixteen3.272.06
  • A function not named costs nothing, however many are bound. In Rust, $a + $b takes 0.40 µs with one, four or sixteen functions bound, against 0.39 µs with none (2.82 µs with sixteen before).
  • What stays is Java’s own, about 0.07 µs once the bindings hold a function, whatever their number: the evaluation’s Host in a ScopedValue and the frames’ thread-local set in Rust.

Audits (0.25 #8)

Audits follow the Python and WebAssembly packages’ evaluate_with_audit, through one more export, jlens_evaluate_audited (audit.rs in jlens-capi):

  • The input crosses whole. The core audits an evaluation of JSON values, and the header hashes the input’s JSON text, so evaluateWithAudit writes its Java objects as values first (the encoding of 0.25 #7’s bindings), not through the reader of 0.25 #6. A Document is refused: it may be pruned, and its hash would not be the input’s.
  • One reply of values. Rust writes the result, the error, the audit tree and the explanation as one object of values, which Java decodes with Values and turns into records. The error is its envelope as JSON text, the one JlensException already reads. The tree’s spans are UTF-16 offsets, converted in Rust with a table of the source’s offsets.
  • Records, and a sealed interface for decisions. AuditResult, AuditTree with its Header, AuditNode, Explanation with its Line, AuditOptions, CaptureLimits and Span are records; levels, outcomes and branches are enums. The ADR’s Decision said that an AuditNode would be a sealed hierarchy. It is one record instead, since every node has the same fifteen components; what a node decided is the sealed hierarchy, AuditNode.Decision: a Comparison with its two operands, a ShortCircuit, a Conditional with its branch, or a Binding with its variable, null for a node that decided none of these. The core sets at most one of the four fields, so a switch over them is exhaustive.
  • Errors are reported, not thrown, as in Python and WebAssembly: an error of the evaluation is the result’s error, a JlensException. A host function’s exception does not throw either; the error has its code, and the exception as its cause, the same object.
  • Deep trees. An audit nests as deep as the evaluation did. Java builds the nodes from a queue, children first, never by recursion, and AuditNode.toString prints one node, not its descendants. A full audit of a recursion 1,000,000 calls deep stops with D1011, and one 10,000 calls deep succeeds with a truncated tree, on threads of 128 KiB and 1 MiB.

Measured on the maintainer’s Windows machine, Java 25.0.4, the rule of the Python and WebAssembly suites on its order of three items, as Java objects, with one variable bound. Microseconds per evaluation, the best of five runs of 0.3 s, and the Python package’s evaluate and evaluate_with_audit on the same machine:

EvaluationJava µsPython µs
evaluate, no audit5.83.6
audited, level off22.815.5
audited, level decisions49.340.6
audited, level full188.8190.3

An audit at level off costs 17 µs more than an evaluation: the input written whole and hashed, and the tree and the explanation written, read and made into records. Java’s part is about 7 µs more than Python’s at off and decisions, and nothing at full, where capturing values in Rust dominates.

The allocator outside Windows (0.25 #11)

Found while testing the JAR (#12): mimalloc 3.3.2, the version libmimalloc-sys 0.1.49 bundles, crashes on glibc in a library loaded at run time once the thread that loaded it has ended. A later thread’s first allocation finds a heap whose thread data is null and faults in _mi_subproc, with the local_dynamic_tls model as with initial-exec. The JVM crashed at the third short-lived thread after the loading thread ended; the Python package 0.24.0 segfaults when import jlens runs in a thread that ends. Windows and musl do not crash, nor does the jlens command, an executable. The suites never saw it: their threads live as long as the run.

ThreadsTest.loadedOnAThreadThatEnds and test_loaded_on_a_thread_that_ends load the library on a thread that ends, then evaluate on eight new threads, one after another, in a new process. Both fail with 3.3.2 on glibc (the JVM aborts with 134; the PyPI wheel of 0.24.0 and a wheel built with maturin build exit with 139) and pass with every candidate below.

Decision: mimalloc 2 (2.3.2, the crate’s v2 feature) in jlens-capi and jlens-python on every target but Windows, where mimalloc 3 stays. One target-specific dependency in each Cargo.toml, no code. The jlens command keeps mimalloc 3: its release binaries are built alone (-p jlens-cli), while a build of the whole workspace on Linux unifies the feature and gives it mimalloc 2.

The C API’s evaluations through its exports, as in the table of #2: JSON text copied into a buffer per evaluation, then a Document. Microseconds, the best of two alternated runs, each the best of five runs of 0.3 s after a second of warm-up. 3.6.0 is upstream’s release of 2026-10-23, put in place of 3.3.2’s sources in a copy of libmimalloc-sys; it passes the regression tests.

Linux (WSL, glibc):

ItemsExpression3.3.23.6.02.3.2jemallocglibc
1,000items[0].name307292297355381
1,000$count(items)207206205238222
1,000$sum(items.price)338324329366378
1,000items[price > 98].id470457462500510
1,000$1,8341,7921,7592,0472,223
100,000items[0].name34,04933,13233,99344,65039,727
100,000$sum(items.price)37,43435,82337,14045,70340,780
100,000$216,536210,379209,392264,134255,974
100,000$sum(items.price), Document5,5915,2045,1707,18810,503
100,000$, Document123,499121,221116,460145,703151,893

Windows (the system allocator from a pair of runs alternated with 3.3.2 and 2.3.2 alone):

ItemsExpression3.3.23.6.02.3.2System
1,000items[0].name318296344441
1,000$sum(items.price)339333366448
1,000$1,9731,9411,9973,006
100,000items[0].name34,48833,54438,59454,764
100,000$sum(items.price)36,47736,36641,96457,964
100,000$226,735223,382267,865437,288
100,000$, Document125,484131,275135,176248,734

The Python package with Python values in (python.py speed, WSL, Python 3.14, the median of three alternated runs): with mimalloc 2, every case takes the same time as with 3.3.2 within 1%, or less: recursion 682 µs against 734, the index cases 0.1 µs less; the wheel is 7 KB smaller.

  • On Linux the three mimalloc versions are within 8% of each other, mimalloc 2 the fastest on $ and on a Document. jemalloc (tikv-jemallocator with disable_initial_exec_tls) is 8 to 39% slower than mimalloc 2, and glibc’s allocator 8 to 103%.
  • On Windows mimalloc 2 is up to 18% slower on JSON text, and 8% on $ over a Document; 3.6.0 is within 5% of 3.3.2. Since 3.3.2 does not crash there, Windows keeps it.
  • 3.6.0 was not taken, though it passes: libmimalloc-sys has not published it, so it would mean carrying a copy of the crate with upstream’s C sources, through [patch.crates-io], for the whole workspace and the Python package’s source distribution; and it is two days old, its release notes silent on this fault. When libmimalloc-sys bundles a v3 that passes the two regression tests, every target can move back to one version.
  • macOS takes mimalloc 2 too, unmeasured here: whether 3.3.2 has the fault there was not tested, and mimalloc 2 is the version known to pass.

The JAR (0.25 #12)

.github/workflows/jar.yml, called by CI on each push to main, builds the C API of the seven release targets as the wheels are built, packs them in one JAR, then runs the JUnit suite on each target against that JAR: the suite’s classes are compiled, the package’s replaced by the JAR’s, and LoaderTest checks that the loader picked the platform CI names in JLENS_TEST_PLATFORM. The JAR’s directories are Rust’s {OS}-{ARCH}, with -musl after them on musl (linux-aarch64-musl).

  • glibc 2.28, as the manylinux wheels: the glibc libraries are built in the manylinux_2_28 containers, with Rust installed there by rustup, and the job fails when a symbol needs a newer glibc than 2.28.
  • musl is built in rust:alpine. A library loaded by a JVM linked against musl must link musl dynamically (-crt-static off), and then Rust links its unwinder from libgcc_s, which Alpine’s JDK packages do not depend on: of the Alpine JDKs, only Temurin’s brings it. A linker script named libgcc_s.so, put first on the search path, links Rust’s own libunwind.a, the one a static build uses, so the library needs musl alone, which the job checks. The export tests, built the same way in the same container, check that a panic is still caught (U2004). The suite runs in alpine:3.24 on its openjdk25-jdk, which has no libgcc.
  • The loader tells musl from glibc by the dynamic loader mapped into the process (/ld-musl- in /proc/self/maps). Files on disk do not tell: a glibc system can have musl installed.
  • Extraction. The library is copied to jlens-<user>-<SHA-256 of its bytes> in java.io.tmpdir. Each JVM writes its own temporary file there, then moves it in place atomically; a failed move is accepted when the file in place has the library’s size, as on Windows, where a library another JVM moved in first and holds open cannot be replaced. The temporary directory is shared on Linux and macOS, so another user could make the directory first and put a library of their own in it: the loader makes it with permissions rwx------, and refuses one that is a link, that another user owns (compared with the owner of a temporary file it makes) or that the group or others may write to, with an UnsatisfiedLinkError that names the ways out (remove it, or set java.io.tmpdir or jlens.library). Windows has no POSIX permissions there; its temporary directory is the user’s own.
  • LoaderTest: the platform detected has its library in the JAR; eight JVMs started at once leave one library and no partial file; a directory others may write to is refused, then accepted again once restored.

Run locally against one JAR carrying the Windows, glibc and musl x86-64 libraries, all 57 tests pass on Windows, in WSL (glibc, against the manylinux_2_28 library, whose newest glibc symbol is 2.28) and on Alpine 3.24 (openjdk25-jdk, and earlier Amazon Corretto’s Alpine build). Before #11, the glibc run crashed in mimalloc 3. ARM and macOS run in CI, and macOS on ARM also on a MacBook Air M1.

macOS on ARM: room for the JVM below a call back. The first CI run failed one test there, only there: $string($) over Java lists nested 2,000 deep, on threads of 128 and 256 KiB, failed with U1004, the reader’s StackOverflowError; when the reader’s handler overflowed too, the exception left the upcall and the JVM aborted (upcallLinker.cpp, “Unrecoverable uncaught exception”). HotSpot sizes its guard zones and its shadow zone in 4 KiB units rounded up to the page size, and macOS uses 16 KiB pages on ARM: Java needs about 128 KiB free below the caller’s frame there (red, yellow and reserved zones 48 KiB, shadow zone 80 KiB), against 96 KiB with 4 KiB pages. jlens_core::stack::grow moves to a new segment when less than 128 KiB is left, and the crash report showed exactly 128 KiB free at the call. Every call back into the host, the reader’s and host functions’, now goes through upcall in jlens-capi, which moves to a new segment of 4 MiB when less than 256 KiB is left. The core keeps its 128 KiB. Host functions never failed, at any depth from 0 to 3,000 on either stack, but take the same route. On Windows the calls cost the same within noise (items[0].name over Java objects 2.48 against 2.49 µs, $sum(items.price) over 1,000 items 324 against 316 µs, a host call 1.73 against 1.71 µs, the best of three alternated runs).

The JAR’s size: each library is about 3 MB, about 1.1 to 1.25 MB compressed (Linux x86-64 3.19 MB, 1.22 MB in the JAR; Windows 2.74 MB, 1.07 MB), so about 8.5 MB for the seven, more than the 7 MB the decision estimated. Per-platform JARs remain the way out if users ask.

Maven Central (0.25 #13)

The Release workflow publishes the package as io.github.thkprado:jlens through the Central Portal, in a job that needs every other build of the release, the JAR workflow’s included: the seven libraries built and the suite passed on each target against the JAR. The Portal has no trusted publishing, unlike npm and PyPI, so the job’s environment, maven-central, holds a user token of the Portal and the release key; its rules accept only v* tags.

  • The profile release of pom.xml adds the sources JAR (the Java sources alone: by default the plugin also packs the resources, the 8.5 MB of libraries), the Javadoc JAR, a signature of every file and the upload. The signatures are made by maven-gpg-plugin’s BouncyCastle signer from the key in an environment variable, so the runner needs no gpg and no keyring.
  • The maintainer publishes. The upload is a deployment that the Portal validates (the POM’s metadata, the signatures, the checksums) and then holds (autoPublish false). A version published on Maven Central can never be removed or replaced, so the last step is a person’s, as the GitHub release is a draft.
  • The JAR published is the JAR tested. The job builds the JAR again from the libraries the JAR workflow packed and compares it with that workflow’s, byte for byte; pom.xml fixes the time of the JAR’s entries, which makes two builds from the same files the same bytes (checked on Windows: two clean builds, with and without the profile, gave the same SHA-256).
  • Versions. CI’s Java job fails while pom.xml and the workspace differ (cargo xtask java), and the release job checks both against the tag.

Run locally with a key made for the test and -DskipUpload=true, the profile built the bundle the Portal takes: the JAR, the sources (48 KB) and Javadoc (318 KB) JARs and the POM, each with its .asc and its MD5, SHA-1, SHA-256 and SHA-512 checksums; gpg --verify accepted the signatures. The first upload is 0.25.0’s (#16).

Amendment: maps written with what the expression reads (0.26 #4)

Context

Over Java maps, jlens took 1.4 to 7.5 times as long as over a Document on the cases that read the order’s items, with one call back into Java for each field it read. Measured on Windows with Java 25, one call back costs about 300 ns: 28 ns for a bare Panama upcall, about 85 ns in the C API (finding the level’s buffer by its handle takes the table’s lock, then the buffer’s) and about 95 ns in Java (115 with a string). The cases of benches/cases.json, over 200 items, made 202 calls (names over items) to 1,406 (the shipping rule) per evaluation.

Writing a small map or list whole with the level that holds it, one level deep, cut the calls to one to three, and the shipping rule’s time by a third to a half. It made the cases that read one field of each item 8 to 20% slower (names over items, regex), and number formatting, which reads 20 items of 200, two to three times slower: Java writes a map’s entry in about 30 ns, so six entries cost about one call.

Decision

  1. A map or list is written with what the expression reads of it (ADR 0016), when it is a value of the level written, not of the contents of another, so that the C API reads it without calling back:
    • a map of which the expression reads some fields, with those fields (OBJECT_SOME, at most 16, whatever the map’s size), a field it reads that the map lacks as UNDEFINED;
    • a map read whole, of at most 16 entries, whole (OBJECT_WITH), and a list of at most 16 items with its items (ARRAY_WITH);
    • a map or list the expression does not read, as a reference, its number.
  2. The expression’s reads are found once, at its first evaluation over Java objects (Expression.reads()), and made ready for the reader: each field’s key in UTF-8 and the reads of its value.
  3. The result never depends on the analysis. The C API calls back for a field that was not written and for the map whole. A host function named after a built-in, which the analysis takes for the built-in, gets its argument whole. The tests prove it with a host that writes every other field and a field that no object has (SOME in tests/host/mod.rs), against the same evaluation on JSON text.
  4. The C API keeps the last buffer it read a level from, which saves the table’s lock on each call (17 ns).

Tried and dropped: a pattern switch replaced with instanceof tests, and strings encoded by an ASCII loop (4 ns a character, slower than getBytes) or through a cache of 64 keys’ UTF-8, which distinct values evicted.

Consequences

Microseconds per evaluation with cargo xtask java-compare cases over Java maps parsed by Jackson, on the maintainer’s Windows machine, Java 25.0.4: the median of three runs alternated with the code before the change. The Document column, which this does not touch, measured within 2.5% between the two, recursion aside:

CaseBeforeAfterChange
path1.681.680%
names over items66.830.4−54%
filter + aggregate15398.6−36%
group-by243142−42%
sort + map547376−31%
strings179139−22%
regex206159−23%
number formatting48.556.0+16%
object constructor294190−35%
transform716696−3%
recursion863889+3%
shipping rule484235−51%
index into 10,000 items2.532.44−4%
index in a variable2.912.83−3%
  • On the spike’s documents (java-compare documents, two alternated runs), $sum(items.price) takes 146 instead of 324 µs on 1,000 items and 19.6 instead of 43.9 ms on 100,000, now 2.7 times as long as over a Document, against six times; items[price > 98].id 273 instead of 407 µs; items[0].name 2.3 instead of 2.5 µs, the input’s one field written with it.
  • On threads (java-compare threads, one run each), $sum(items.price) on Java objects that Jackson parses from 100 items at each evaluation gives 98,085 evaluations per second on 16 threads instead of 73,479, and 10,931 on one instead of 9,131.
  • Number formatting takes 16% longer: items[[0..19]] reads the list of 200 items whole, so each item is written with the two fields the expression reads, and 20 are used. Since 0.27 #8 the list is not read whole: 57.5 → 33.4 µs (ADR 0010).
  • $ takes 1.00 instead of 0.75 µs: the input, a map of one field read whole, is written with that field, which the result, the input itself, does not need.
  • recursion reads no input, and takes 3 to 4% longer with a Document too: the C API library’s layout, not the reader.
  • Benchmark harness. cargo xtask java-compare put every JAR in the harness’s target/deps on the classpath, and a JAR of an earlier version stayed there: on Windows the harness loaded jlens-0.24.0.jar, built on 2026-10-25 at 0.25 #6, from the version bump of 0.24.1 on. The command now empties the directory first. In one run, that JAR measured within 4.3% of the code before the change on the cases above, over Java maps and over a Document, but for names over items over a Document, 9.6% faster: the Windows measurements from 0.25 #12 on are close, though not of the code they name. The performance page’s Java tables were measured under Linux, whose order of deps/* is the directory’s; 0.26.0 measures them again.

Results: a host’s input that never ends (0.26 #9)

The C API reads a host’s arrays and objects as the expression reaches them, and trusted the host to bound them. A reader that answers a node with a level holding that same node, an array inside itself, made a.b flatten arrays for ever. The Java package refuses a map or list inside itself when its Reader writes it, so only a C API host that misses a cycle was exposed, and the property test whose reader returns any bytes could hang, rarely.

  • Each node has a depth, one more than the level that last wrote it (the input’s level is depth 1), kept in a table by node number. Reading a node deeper than 1,000 levels, as deep as JSON text is parsed, fails with U1004. A node inside itself is written again at each read, one level deeper each time, so it stops there. The C API cannot tell a cycle from deep input, and the message names both.
  • The table stays as long as the levels. The host numbers its nodes from 0 as it writes them, so a node numbered past the bytes of the levels read so far is out of the form and fails with U1004; before, it was only not held (the CI fix of 0.26 #4).
  • Over Java objects, a map or list nested more than 1,000 levels deep fails with U1004 when it is read. $string($) on input nested 2,000 or 100,000 levels still fails with U1001, as the core stops writing before it reads level 1,001, so the limits table does not change.
  • The cost is a write per array or object of a level and a look-up per read. With cargo xtask java-compare cases, the median of three runs alternated with the code before, over Java maps each case took 0.5 to 4.4% longer (median 2.5%), and over a Document, which the change does not touch, 0 to 3.4% longer (median 0.9%): about 1 to 2%, within the 4.5% by which two builds of the same library differ (0.26 #7).

Results: a reply in one call, and handles found without a lock (0.26 #10)

Beyond the evaluation, the C API took about 0.19 µs of the 0.44 µs customer.name took from Java against a Document (0.26 #7). About 110 ns of it was the reply: a new buffer for it (an allocation and the lock of the buffers’ table), which Java then read with three more calls, its address, its length and its release, each finding the buffer again behind that lock. The rest was mostly finding the expression and the document, each behind the lock of its table, shared by every thread.

  • The evaluations reply into a scratch buffer that the host passes as a last argument (jlens_evaluate, jlens_evaluate_document, jlens_evaluate_source). A reply that fits is written at its start, and the export returns its length in the high 32 bits with the low 32 bits 0, which no handle has: the host reads it with no further call. A reply that does not fit, any reply when the scratch is 0 or unknown, and the reply of a panic come in a buffer of their own, as before. The scratch is a buffer of the C API, known by handle, so Rust still dereferences no pointer the host gives it.
  • Java keeps a pool of scratch buffers of 4 KiB in Native: 64 slots, chosen by the thread’s id, each 16 entries apart so that two slots share no cache line. An evaluation takes its slot’s buffer, or makes one when the slot is empty (another thread with the same slot, or an evaluation inside a host function’s call), and puts it back, or frees it when the slot was filled meanwhile. At most 256 KiB stay, for the life of the process. A buffer per ThreadLocal was not chosen: virtual threads would each make one, and a host function that evaluates needs a second buffer on the same thread.
  • Each thread finds its objects again without the lock. A table also keeps each entry’s live handle where any thread reads it with one atomic load (chunks that double in size, made under the lock and never moved, so no unsafe). An evaluation looks the expression, document, options, bindings and scratch buffer up in a cache of its thread, at most eight objects, held as Rc<Arc<T>>: a hit is that load and a short search, and writes nothing other threads read, neither the table’s lock nor the object’s reference count. A miss takes the lock, as before. A removed object stays in a thread’s cache until that thread next looks up in the same table, which drops what was removed; for documents, every export does it first, so a freed document is still dropped, with its conversions, once each thread that used it calls again.
  • The cost of one call, timed from Rust: customer.name against a document, its reply read and freed, 383 → 273 ns (the evaluation and its encoding alone take 206 ns), 1 300 → 199 ns. Evaluations per second of customer.name on one Document shared by Java threads: on 1, 4, 8 and 16 threads, 2.2, 3.6, 1.3 and 1.0 million before, where 16 threads did less than one; 2.8, 5.7, 6.1 and 3.1 million with the scratch reply alone; 2.9, 6.7, 12.3 and 20.8 million with the handles found without the lock (two runs of each, alternated). java-compare threads, whose evaluation of 100 items of JSON text takes about 43 µs, moved within its noise (±4%).
  • The cases, with cargo xtask java-compare cases, the median of three runs alternated with the code before: on a Document, customer.name 0.47 → 0.34 µs, the indexes into 10,000 items 0.78 → 0.70 and 1.10 → 1.05 µs, recursion 3.4% less, the other cases from 2.3% less to 0.7% more; from JSON text and over Java maps, from 2.6% less to 1.7% more. Over Java maps parsed from JSON text by Jackson, customer.name and the indexes measured 1.7 to 2.1% slower, within the spread of their runs (customer.name 97 to 109 µs before, 102 to 105 µs after; the indexes 1.7 to 2.1 ms in both), where the scratch reply alone had measured customer.name 7% faster.

Amendment: documents as variables (0.35 #7)

Context

An evaluation took one Document, its input. An application that receives two documents as JSON text, such as two versions of a record, or a record and a table it refers to, had to give the other as a variable of Bindings: parsed into Java maps and lists, written to native memory when the bindings are built, and converted at each evaluation as far as the expression reads it (ADR 0019). That builds bindings for each pair of documents, where bindings are made once to serve every evaluation, and a field read of each item of an array converts the array. The core has bound documents to variables since 0.21 (evaluate_document_with), with none of it.

Decision

  1. The call is Expression.evaluate(Document input, Map<String, Document> documents), then with Bindings, then with Bindings and Options, and evaluateJson with the same arguments. A map, not a builder or a type of its own: the documents change from one evaluation to the next, so there is nothing to build ahead, and a map is what an application holds. A name is given with or without its $, as Bindings.Builder takes it. null as the input is no input, as Document::undefined() in the core: the expression runs on its variables alone.
  2. Precedence is the core’s: a document takes the place of a variable or a host function of the same name in the bindings, for that evaluation, and the bindings are not changed.
  3. The C API gets one export, jlens_evaluate_document_with(expression, document, documents, bindings, options, result, scratch), with document 0 for no input; jlens_evaluate_document stays as it is. documents is a buffer that lists the documents: their number, then the handle and the name of each. It is binary, not JSON text as the declarations of a language service are, as it is written and read at each evaluation. A list not in its form fails with U2005, and a document it names that was freed with U2002.
  4. The list may be the scratch buffer of the same call: it is read whole before the evaluation starts and the reply is written after it, and the bytes after the last document are not read. Java writes the list at the start of the scratch it takes from its pool, so the documents cost no call beyond the evaluation’s; a list of more than 4 KiB goes in a buffer of its own.
  5. Threads. A thread converts a document the first time it evaluates with it, as the input or as a variable, and keeps the conversion until the document is closed, as before (0.25 #3): bound to a variable, a document is an Rc clone of that conversion.
  6. Left out. Audits keep their variables in the bindings, as the core audits JSON values. An evaluation over Java objects takes no documents, as evaluate_source takes none in the core. A part of a document as a variable (Document::pointer) is not in the package either. The Python and WebAssembly packages are items of their own, when one is asked for.

Consequences

  • What a Document saves is the conversion, at each evaluation, of what the expression reads of the variable. On the M1, with $table the spike’s document and a small document as the input (cargo xtask java-compare variables, a part of the harness run when named): $table.items[0].name takes 68 µs with the variable in Bindings and 0.6 µs with it a Document on 1,000 items, 8.3 ms and 0.8 µs on 100,000; $sum($table.items.price) 69 and 8.3 µs, 9.2 and 3.4 ms.
  • A bound document costs 50 to 75 ns of a call, read or not, timed from Rust: 1 takes 129 ns against a document, 219 ns with one more bound and 269 ns with two. The list is copied in two allocations however many documents it names. About 17 ns were the core’s, which put the root frame on its list of frames that may be part of a cycle for any array or object bound there; 0.35 #9 binds them without it, about 15 ns less for each evaluation.
  • evaluate(Document) with no documents measures as in 0.34.0: java-compare ab on the documents and the cases marks no difference but regex, 5.4% faster (perf-0.35.md).
  • The robustness properties of the C API call the export with lists in their form, of documents live and freed, and with any bytes as the list.

0022 — Objects keep their fields in a vector, with an index past 8 fields

Status: Accepted.

Context

Every object jlens builds or converts holds its fields in an IndexMap<Rc<str>, Value> hashed with foldhash: a vector of entries and a hash table of their positions, each allocated apart. Tuples are such objects, one per item, and so is each match $match returns. A lookup hashes its key, whatever the size of the object.

Roadmap 0.31 #1 counted what objects hold at 0.30.0 (notes):

  • No object the benchmark workload builds, converts or reads has more than 6 fields. Of the 483 objects of the JSONata test suite’s datasets, 86% have 3 fields or fewer, 99.6% 6 or fewer, the largest 11.
  • Lookups matter as much as construction: a path over the items looks its key up in each item.
  • The hash table is one of the 7 allocations of an object built by a constructor, one of the 4 of a match of $match, and one of the 3 of a tuple. The map makes an Object 104 bytes, 64 of them the IndexMap and its hasher.

Objects can still be large: a document whose keys are identifiers has thousands of fields in one object, and reading or building it must stay linear.

Decision

  1. A map of jlens’s own, jlens_core::map::Map, private to the crate: the fields in a vector, in insertion order, with their shared Rc<str> keys. A lookup compares the key’s length with each field’s, then its text. Its operations are those of IndexMap that jlens uses, with the same meaning: a key inserted again keeps its position and its first key, shift_remove keeps the order, swap_remove moves the last field into the gap.
  2. An index past 8 fields. A map of more than 8 fields keeps the position of each key in a hashbrown::HashTable<usize> hashed with foldhash, in one allocation apart, built whole when the map passes 8 fields and dropped when a removal brings it back to 8. Measured on 0.31 #2 (below), up to 8 fields a search in order finds a key present faster than foldhash, one absent within about a nanosecond, and builds the map faster.
  3. No fields kept in the object itself. The fields stay in the vector’s allocation.
  4. No hasher in each map. A map without an index has no hasher; an index makes its own RandomState. The hasher that the lazy values of one evaluation share (ADR 0010) goes away with IndexMap.

A property test runs random operations on the map and on IndexMap and compares their answers, fields and order after each. IndexMap stays for the maps that are not objects (the groups of group-by, the host functions).

The measurements

Ryzen 3700X, Windows, the system heap; times of one lookup in a map of n fields with keys of the workload’s kind (code, customer, …), averaged over every key, and of building a map of n fields with a check for duplicates, dropped after.

FieldsKey present: in order / foldhashKey absentBuilding
15.1 / 6.5 ns2.3 / 4.5 ns35 / 86 ns
36.3 / 10.94.5 / 5.743 / 115
67.5 / 11.05.7 / 5.860 / 164
88.6 / 11.27.1 / 5.875 / 192
1211.4 / 11.210.4 / 5.8128 / 256
1613.4 / 11.714.2 / 5.8189 / 319
6436.6 / 12.144.1 / 6.32,302 / 1,048

With mimalloc, building costs 10 to 37 ns in order against 51 to 134 ns with foldhash up to 6 fields. Fields kept in the object were measured too: 3 or 4 of them save 10 to 20 ns per object of 2 or 3 fields on the system heap, nothing with mimalloc, cost 20 to 40 ns per object that holds more (the workload’s items have 6), and make each small object about three times larger.

Consequences

  • An object takes one allocation fewer, and an Object 72 bytes instead of 104. A lookup in an object of 6 fields or fewer hashes nothing.
  • An object of more than 8 fields costs what it cost: a vector, a table, a hashed key per lookup. Between 9 and about 12 fields, a key present is found as fast either way.
  • hashbrown becomes a direct dependency of jlens-core; it was already in its tree, through indexmap.
  • Nothing public changes. deep_eq and $distinct can compare two small objects field by field (roadmap 0.31 #4).

Alternatives

  • Keep IndexMap. It keeps the hash table and the hashed lookups that the measurements show slower for the objects jlens meets.
  • No index at all. An object of thousands of fields would be quadratic to build and slow to read.
  • Fields in the object, a SmallVec. Measured above: a gain on the system heap only, a loss with mimalloc and for larger objects, and three times the memory of a small object, which a document of 10,000 items pays 10,000 times.
  • Keys sorted, searched by halves. The fields keep their insertion order, which JSONata shows; a sorted copy would be a second allocation, as the hash table is.

0023 — The schema and the language service through the C API and in the Java package

Status: Accepted (2026-11-10).

Context

The Java package left the schema and the language service out (ADR 0021; “What the package leaves out” in its guide), to be added when a Java application asked for them. One does now. It stores expressions written against a schema that another system sends it, and when a new version of the schema arrives it checks each stored expression again, on a server (roadmap 0.33): does the expression still pass the diagnostics, and did anything it uses change?

jlens-schema answers the first question in Rust, and the WebAssembly package and the language server give its answer to editors. Roadmap 0.33 #5 and #6 add the second: what an expression uses of its schema, and what changed in that between two schemas. A Java application reaches none of this today but by running jlens check as a process.

What jlens-schema has, and what each part would cost to carry:

  • A Schema, read from a JSON Schema document (Schema::from_json_schema), or inferred from sample documents (Schema::infer, apply_overrides).
  • A LanguageService, made of a schema, the variables the expressions are evaluated with (each with the shape of its value, or none) and the host functions declared to it. It gives the diagnostics of a text, and, at an offset of it, completion, hover and signature help.
  • Both are plain data once made, with no Rc and no interior mutability: Send and Sync, as a compiled Expression is, and unlike a Document.
  • The crates jlens-schema depends on (serde, serde_json, indexmap) are already in the library, through jlens-core.

What it adds to the library’s size, measured with a probe on the C API of 0.32.0 (Windows x86-64, the release build as cargo xtask java makes it; compressed with gzip -9, close to what the JAR’s deflate gives):

LibraryRawCompressed
0.32.03,125,760 bytes1,167,801
With a schema from JSON Schema text, a service and its diagnostics3,287,552 (+5.2%)1,236,293 (+5.9%)
With completion, hover and signature help too3,376,640 (+8.0%)1,272,207 (+8.9%)

The diagnostics bring the JSON Schema reader and the typing, 162 KB; the three editor operations add 89 KB to that. Over the JAR’s seven targets, of about 9.1 MB together, that is about 0.5 MB for the first row and 0.7 MB for both. The code of #5 and #6 is not written yet and is not in these numbers; roadmap 0.33 #11 measures the library and the JAR as released.

Decision

  1. jlens-capi depends on jlens-schema, with no feature to leave it out. One library and one JAR, as now. 5 to 6% of the library does not pay for a second build of seven targets, a second artifact on Maven Central and a loader that tells them apart.

  2. What crosses in 0.33: a schema read from JSON Schema, a language service, its diagnostics, and #5 and #6.

    • Completion, hover and signature help do not cross. They serve a person typing, in an editor, which the WebAssembly package and the language server reach; the Java application that asked checks stored expressions on a server. Carrying them is cheap in size (the table above) but not in surface: five more record types in Java (Completions, its items, the value request and its conditions, Hover, SignatureHelp), their tests and their guide, in an API that ADR 0015 will have to keep. They can be added the same way (the text in a buffer, a UTF-16 offset, a JSON reply) when a Java application serves an editor.
    • Schema inference does not cross either, nor the overrides: jlens schema infer writes a JSON Schema from samples, and that file is what a Java application loads.
  3. Two new kinds of object, known by handle as the others are: a schema and a service.

    • A schema is made from the JSON Schema text in a buffer (jlens_schema_new; since 0.33 #10 with a second buffer, its sources, as ADR 0025 describes) and freed by its own export. It is a kind of its own, not an argument of the service, because a load has results of its own, which later items give by its handle: the documents a $ref named and the application did not give (#9), the keywords the load did not read (0.34 #8). Those items also change what a schema is made from (other documents, by URI), which then changes one export.
    • A service is made from a schema’s handle, 0 for none, and the JSON text of its declarations in a buffer, 0 for none (jlens_service_new): an object with variables, an object from each name to the handle of the schema of its value, written as a decimal number, or null for a variable declared with no schema; and functions, an array of declarations with the fields of the WebAssembly package’s FunctionDeclaration (name, signature, params, summary). Names are taken with or without $. An unknown member fails, as it does in the options, so that a misspelt one does not pass unnoticed.
    • Neither can be changed once made. A new version of a schema is a new schema and a new service.
  4. Lifetimes. A service keeps what it needs of the schemas it was made from: freeing a schema, before or after, does not affect it. Whether it shares the schema or copies it is not visible to the host; #3 chooses, measuring the copy on the largest fixture. A call that runs on another thread keeps the object it uses until it returns, as an evaluation keeps its expression. In Java, Schema and LanguageService are AutoCloseable with a Cleaner behind them, as the package’s other native objects.

  5. Threads. One schema and one service serve every thread, platform or virtual, with no lock held while they work and no copy per thread: they are Send and Sync, which a test of jlens-capi asserts at compile time. Their tables are locked only to find an entry. The per-thread caches that evaluations find their objects in (ADR 0021, results of 0.26 #10) are not used here: they saved a lock on calls of under a microsecond, and a call that types an expression is not one.

  6. The form of what crosses is JSON text, in both directions.

    • The expression’s text crosses as UTF-8 in a buffer, as a source does for jlens_compile.
    • Diagnostics (jlens_service_diagnostics) are replied as the JSON array the other packages give: each with severity, code, message and span. A text with a syntax error is not a failure of the call: its errors are diagnostics. The package’s own JSON reader decodes the reply into records; the values encoding (ADR 0021, results of 0.25 #5) is for results, which may be large and are the caller’s data, and a list of diagnostics is neither.
    • Spans are UTF-16 offsets, converted by the C API, as an error’s position and an audit’s spans are: a Java String indexes them with no conversion.
    • What an expression uses of its schema (#5) is replied by the service as the one JSON form that item defines, the same from every package (#7).
    • What changed between two schemas (#6) takes two of those JSON texts in buffers and no handle, as jlens_union_reads does for reads: an application can store an expression’s answer beside it and compare it with a new schema’s answer when the old schema is gone. In Java the answers are records that give their JSON text back, as Reads does.
    • These replies come in a buffer of their own, not in the evaluations’ scratch buffer: reading one costs three calls more, against the typing of an expression.
  7. Failures use the C API’s codes. Text that is not JSON fails with U2001; a JSON Schema that jlens refuses, or declarations not in their form, with U2005, whose token says which (schema, service), and whose message is the load’s; a handle unknown or freed with U2002; an expression that is not UTF-8 with U2003. In Java, Schema.fromJson throws a JlensException with the code, as Document.fromJson does for text that is not JSON.

  8. A host that uses none of this pays the size and nothing else. No evaluation export changes, nothing is added to guarded, and the two tables are empty statics.

Consequences

  • The library grows by about 5% and the JAR by about 0.5 MB, before #5 and #6.
  • The Java package gains Schema, LanguageService, a Diagnostic record and the records of #5 and #6, with the same codes, messages and spans as the WebAssembly package, the language server and the CLI. A test pins the JSON that each gives for the same cases (#7).
  • The guide’s “What the package leaves out” shrinks to completion, hover, signature help and schema inference, with where each is found.
  • The C API stays free of Java specifics: another host that calls C gets the diagnostics with the exports of this ADR and a JSON reader.
  • The schema being its own object, the load reports of #9 and of 0.34 #8, and the expected result type and context path of 0.34 #4 and #6, which are more declarations of the service, need no new kind of object.
  • The Python package still leaves the schema and the language service out. It would carry them the same way, a schema and a service as objects and JSON-shaped answers, when asked.

Alternatives

  • One call that takes the schema’s text and the expression’s and replies with the diagnostics. No object and no lifetime, but the schema is read again for each expression: an application that checks every stored expression against one schema reads it once per expression.
  • A second library, or a Cargo feature, for hosts that want the schema. Decision 1: the size does not justify the second artifact.
  • Diagnostics as values, or through upcalls. A decoder and an encoding more for a reply of a few hundred bytes; upcalls cost 25 ns each and bring the stack room of every call back into Java.
  • The variables’ schemas as JSON Schema text inside the declarations, as the WebAssembly package takes them. The Java Schema would have to keep its text to pass it again, and from #9 on a schema is no longer one text.
  • The whole language service now. Decision 2: no Java application asks for completion, and each operation is surface to keep.

Results: the exports (0.33 #3)

Five exports: jlens_schema_new, jlens_schema_free, jlens_service_new, jlens_service_free and jlens_service_diagnostics, in jlens-capi’s schema module.

  • A service copies its schemas (decision 4). Sharing would put the schema behind an Arc in jlens-schema’s LanguageService, a change to that crate’s API for every user; the copy is made once per service and costs about a sixth of what loading the schema does. On the repository’s largest schema fixture (fixtures/cli/order.schema.json, 2.4 KB): the load 22 µs, the copy 3 µs. On generated schemas of 200 and 2,000 fields (28 KB and 224 KB of text): the load 0.78 and 6.5 ms, the copy 0.13 and 1.1 ms (Ryzen, the release profile, the best of seven runs).
  • The handle of a variable’s schema is a JSON number, read as an unsigned 64-bit integer; a string or a fraction fails with U2005. A host whose integers are signed writes it unsigned (Long.toUnsignedString in Java). The declarations must be an object: an array fails too.
  • A handle named inside the declarations is checked after their form, as it cannot be read before: declarations that are not JSON fail with U2001 even when a variable would name a freed schema.
  • Measuring the copy found the diagnostics quadratic in an object’s fields: each field step listed the fields of its context, and the list was built by comparing every name with every other. One step against the object of 2,000 fields took 3.3 ms; with a look-up by name it takes 17 µs, the same as with 30 fields. A field the schema does not have still reads every name, for its suggestion (1.4 ms there). The diagnostics of 1 take about 17 µs with any schema, a fixed cost whose cause was not looked for; roadmap 0.34 #10 measures the diagnostics.
  • The size. The Windows library is 3,346,432 bytes, 7.1% over 0.32.0 (1,258,732 compressed, 7.8%), where the probe had measured 5.2% and 5.9%: the exports read the declarations and write the diagnostics as JSON, which the probe did not. Decision 1 stands; roadmap 0.33 #11 measures the library and the JAR as released. No evaluation export changed.

Results: the Java package (0.33 #4)

Schema, LanguageService with its builder, and the Diagnostic record with its Severity.

  • A function is declared by its name and its signature alone. The C API also takes params and summary, which only signature help and completion show, and those do not cross (decision 2): the Java builder has no place for them until they do.
  • The builder writes a variable’s schema as its handle, with Long.toUnsignedString, and keeps the schemas reachable until the service is made. A schema closed before build() throws an IllegalStateException, as any closed object does.
  • The list of diagnostics cannot be changed, and a reply that is not in the form of decision 6 is a bug of the library, reported as an IllegalStateException.
  • No export changed and the library is the one of #3.

Results: what an expression uses, at every end (0.33 #7)

Two exports: jlens_service_uses and jlens_uses_changes.

  • jlens_service_uses takes the expression’s handle, not its text and not its reads: the C API works an expression’s reads out once, when it compiles it, and Java has no bindings that would change them. The WebAssembly package takes the reads, as reads(bindings) there knows which functions do not read their context.
  • jlens_uses_changes takes two buffers and no handle (decision 6). Text that is not JSON fails with U2001; JSON that is not an answer with U2005 and the token uses. An array where an object is expected is refused: Uses::from_json, in jlens-schema, is the one reader of an answer that every end uses, as the derived one takes an array for a struct’s fields in order.
  • In Java the answers are records: Uses and Use, and UsesChanges with PathChanges, UseChanges, Change and EnumChange nested in it. The two sides of a change are before() and after(), new being a word of the language; the JSON form keeps old and new. A value of an enumeration is what the package’s JSON reader gives (a BigDecimal for a number). Uses.changes writes both answers as JSON and reads the reply, so the comparison is the one of the other packages; an answer made by hand with a type JSON Schema does not have fails there with U2005. Java sorts a map’s names by UTF-16 code unit and Rust by UTF-8 byte, so the text of an answer written by Java can differ in order from the C API’s for names beyond the Basic Multilingual Plane: answers are compared by changes or equals, not by their text.
  • The same JSON from each: fixtures/uses/cases.json holds two versions of a schema, of the variables and the host functions, and for nine expressions the answer with the first version and the changes with the second. The Rust crate, the C API, the Java package, the WebAssembly package (in Node.js and in the browser) and the CLI each answer them, and each test compares its answers with the file’s.
  • The size. The Windows library is 3,507,200 bytes, 12.2% over 0.32.0 (1,321,041 compressed, 13.1%), and 4.8% over the library of #3: the answers of #5 and #6, read and written as JSON, add 161 KB, as much as the schema reader and the typing did. Decision 1 estimated 5 to 6% before #5 and #6; roadmap 0.33 #12 measures the library and the JAR as released, and looks at what of these 161 KB the JSON forms cost.

Results: a host function reads only its arguments (0.33 #11)

The results of #7 said that Java has no bindings that would change an expression’s reads. It has: a host function of the C API receives its arguments and nothing else, and the bindings mark it so (HostFunction::without_input), but the reads worked out when an expression is compiled know no function, and take the call of one as reading its context whole. An application whose rules call its own functions then got the whole input as used, and every change of the schema as a change for every rule.

  • jlens_service_uses takes the functions declared to the service as reading their arguments alone, and the context a - of their signature may take. The service already knows them, so the export keeps its two handles and takes no bindings: what an expression uses is a question about the schema and the declarations, asked where no function is at hand to run. LanguageService::uses_of, in jlens-schema, is that answer, and the CLI gives it too, so that the same configuration gives the same answer at both ends. A function that is not declared still reads its context whole, as does one declared with a signature that is not one.
  • jlens_reads takes the bindings, 0 for none, and Java has Expression.reads(Bindings). reads() is unchanged. The evaluations that cut their own input went by it too, as an expression is compiled once for any bindings, and cutting by the bindings of each evaluation would work the reads out at each one; #12 measured it and cuts by the bindings, below. An application that parses a document for several rules gives Document.fromJson the reads with its bindings.
  • The shared cases have $rate(1), which uses nothing, $rate(items[0].price), which uses that field, and $other(items[0].price), a function that is not declared, which uses the whole input. The WebAssembly package answers them with reads(bindings), the bindings holding the declared functions.

Results: JSON text cut by the bindings, and the size as released (0.33 #12)

  • An evaluation of JSON text with host functions cuts its input by the bindings. #11 left it cutting by the reads of the compilation, which keep the whole input for an expression that calls a host function at its top, and the whole item for one that calls it in a step. Measured on an Apple M1, the 23 KB order of the benchmarks parses in 27 to 50 µs cut by the bindings, against 69 µs, and the analysis takes 1 to 8 µs, which an evaluation of 0.3 µs cannot pay each time. So a compiled expression keeps the reads for the first four lists of host functions it is evaluated with, a list known by its functions’ names and signatures, which is all the analysis takes from the bindings: bindings made again with the same functions find them, on any thread. Kept by thread for each pair of an expression and bindings, as first written, 200 rules evaluated in turn paid the analysis each time, 2.13 µs an evaluation against 1.03. Bindings without functions, and none, go by the reads of the compilation, with nothing looked up (notes). Document.fromJson still takes the reads the application gives it.
  • The size. The Windows library is 3,664,384 bytes, 17.2% over 0.32.0 (1,379,571 compressed, 18.1%), three times the estimate of decision 1, which counted the schema reader and the typing alone. The two exports of #7 are 206 KB of it: what an expression uses 96 KB, the comparison of two answers 55 KB, and their JSON forms, read and written, 54 KB. The forms are a quarter of the exports’ size and stay; the comparison, large for what it does, is looked at with 0.34’s measure. The JAR of seven targets, from the release’s workflow, is 10,198,056 bytes, where 0.32.0’s is 8,739,574: 1.46 MB more (16.7%), as the libraries grew, against the 0.5 MB estimated before #5 and #6.

0024 — A recursive schema keeps its $refs as references to definitions

Status: Accepted. Amended by ADR 0025: a target that is not recursive is kept as a definition too when its copies would make the load much larger than the schema, and a $ref that cannot be followed is a reference to a name the schema does not define.

Context

jlens-schema reads a JSON Schema into a tree of shapes (Shape): each field and each array’s items own their shape, and the target of a $ref is copied in its place. A recursive schema, one where a $ref leads back to itself ("$ref": "#", a definition that refers to itself, two that refer to each other), has no such tree. Until 0.32 the load copied 64 levels and failed whole with $ref nesting is too deep, which left an application nothing to check its expressions against (roadmap 0.33 #8). Trees, linked lists, expressions and the Optional[Node] of generated schemas (anyOf: [{"$ref": …}, {"type": "null"}]) are common.

Three ways to hold a recursive schema were weighed:

  • Copy the target a fixed number of levels. The tree stays, but an expression deeper than the bound gets no completion and no warning, and the size multiplies: a node with two references to itself is 2ⁿ shapes at level n, and n definitions that all refer to each other are n! paths before one repeats.
  • Copy lazily, a level when an expression first reaches it. The shapes keep one address each, which the typing relies on, but the schema then changes while it is shared between threads, a walk over everything (**, a value read whole) never ends by itself, and a shape cloned away from its schema loses what it refers to.
  • Keep the reference, by name, and follow it where the shapes are read.

Decision

  1. A recursive $ref becomes a reference by name. Schema has definitions, a map from names to shapes, and Shape has references, the names of the definitions the value may also have the shape of. A value has the shape of any of them, and of the shape itself when it has types of its own: anyOf: [{"$ref": "#/$defs/node"}, {"type": "null"}] is a shape of type null that refers to node, and allOf: [{"$ref": "#/$defs/base"}] beside properties is an object that also has the fields of base. The typing already takes a type as a set of shapes, so the references add members to the set and nothing is merged.
  2. Only what is recursive is a definition. The load finds the $refs that lead back to themselves (the strongly connected components of the graph of references) before it reads a shape. Every other $ref is copied in place as before: a schema that loaded until 0.32 gives the same shapes. A recursive root is itself a reference to the definition #. (Since ADR 0025, a schema whose copies would pass the load’s budget keeps the targets copied most as definitions.)
  3. The names are those of #/$defs/…, and the text of the $ref otherwise. Schema::to_json_schema writes the definitions under $defs and the references as $ref (one) or anyOf (several), and what it writes reads back as the same schema.
  4. Who reads a shape follows its references, with the schema’s definitions at hand: Schema::shape_at, the overrides, the typing (completion, hover, the diagnostics) and what an expression uses. They go as deep as the path or the expression goes. A walk over everything stops where it meets a shape again: ** gives each shape once, and under a value read whole, what an expression uses lists what is under each definition once, at the place nearest to that value, first in the order of the paths.
  5. A reference that leads nowhere is unknown. A name the schema does not define, or references that only lead to each other, leave their place without a shape: nothing is completed and nothing is warned under it.
  6. A variable is declared with its schema (LanguageService::with_variable_schema), as its definitions are read with it. with_variable, which takes a shape alone, stays: the references of such a shape are unknown.

Consequences

  • A path of the overrides that goes through a reference changes the definition, and so every place that refers to it: children[].label in a tree describes the label of every node.
  • Annotations beside a recursive $ref (description, title) describe that field in completion and hover. Other keywords beside it count only with a type: a shape without types that refers to a definition stands for the definition alone.
  • Shape and Schema gained a public field each, and a Schema built by hand must give definitions; ..Schema::default() does. Code that walks Shape::fields and Shape::items by itself does not see through a reference: Schema::members gives the shapes one stands for.
  • What an expression uses of a recursive schema is finite, and still sound for the comparison of two schemas: a change inside a definition shows in the one place it is listed. Where that place is does not depend on the order the schema is written in.
  • A schema nested more than 64 levels without recursion still fails, now with the schema is nested too deep.

0025 — A $ref to another document: the application gives the documents, and the load reports what it did not follow

Status: Accepted.

Context

Until 0.32 jlens-schema followed a $ref only as a JSON Pointer into its own document (#, #/$defs/…). Any other failed the load whole with cannot resolve $ref: a schema split into files, one that names its parts by $id or $anchor, or one with a single $ref to a definition that was removed. An application that checks stored expressions against a schema that another system sends (roadmap 0.33) then had nothing to check them against.

Loading such a schema also met an old bug. The target of a $ref that is not recursive is copied in the place of each $ref (ADR 0024), so definitions that each refer twice to the next double at each level: 20 levels, a document of 1.9 KB, loaded in 2.2 s, and 30 would not end. A document from another system must not be able to do that.

Decision

  1. jlens never fetches a document. The application gives each one with its URI (SchemaLoader::document), and the load reads only what it was given. A library that opens a URL found in its input would give whoever writes a schema a request from the application’s network, and a load whose result depends on the network is not the same twice.
  2. A $ref is resolved as JSON Schema 2020-12 says. Its base is the $id of the nearest schema around it that has one, itself resolved against the one above, and at last the URI the document was given with (SchemaLoader::load_at), or none. A document is known by the URI it was given with and by each $id in it. The fragment is a JSON Pointer from the schema the rest of the URI names, or the $anchor of a schema in it; an $id that is a fragment alone ("$id": "#name") is read as an anchor, as it was until draft-07. Two URIs are the same when their texts are equal once resolved (RFC 3986, section 5.2): nothing is normalized but the dot segments of a path. A base may be relative or empty: with no $id and no URI, common.json#/$defs/person is a place of the document given as common.json.
  3. A $ref that cannot be followed leaves its place unknown, and the load goes on. The place refers to a definition the schema does not have, named by the resolved URI, which ADR 0024 already reads as unknown: nothing is completed and nothing is warned under it, whatever keywords are beside the $ref or merged with it by allOf, anyOf or oneOf, since the missing schema could declare any field. What an expression uses marks the place unknown, so giving the document later shows as a change. Schema::to_json_schema writes such a reference back as the $ref it was resolved to.
  4. The load reports what it did not follow (LoadReport), beside the schema: for each $ref, its place (the document’s URI and a JSON Pointer), its text, the URI it resolves to, and the document that was not given, or none when the document is there without that place. LoadReport::documents lists the documents to give. Only the $refs the load met are reported: one under a definition that nothing leads to is not read. The report is a struct that may grow: the keywords the load does not read are to be reported the same way (roadmap 0.34).
  5. A load is bounded by the size of its documents. Before reading a shape, the load counts the JSON values it would read, each target once for each $ref to it. Within the budget, 16 times the values of the documents and no less than 100,000, every $ref that is not recursive is copied in place, as before. Past it, each target that would read more than its share, the budget divided by the number of $refs, is kept once as a definition, as a recursive one is; the load then reads no more than the documents’ values plus the budget. Failing the load instead was dropped: the schema is valid, and a definition serves it.

Consequences

  • Schema::from_json_schema no longer fails for a $ref it cannot follow; it loads with no other document and drops the report. The two failures left are a document that is not a schema and one nested more than 64 levels deep.
  • A $ref inside a schema with its own $id is now resolved against that $id: a pointer starts at that schema, not at the document’s root. Bundled schemas, which embed each document with its $id, depend on it.
  • A property named $ref, $id or enum is a property: the load tells a map of schemas (properties, $defs, definitions, patternProperties, dependentSchemas) from a schema, and reads no schema under enum, const, examples and default.
  • A schema past the budget has definitions that are not recursive. Their places differ from a copy in what ADR 0024 lists: the keywords beside the $ref count only with a type, an override through one changes every place that refers to it, and under a value read whole, what is under one is listed once. Written back and read again, such a schema may copy in place what it kept, and answers the same.
  • The budget’s worst case, a schema just under it, loads in about 40 ms (a doubling of 14 levels; Ryzen, release build); the same schema with 20, 30 or 400 levels loads in 3 to 4 ms.
  • $dynamicRef, $recursiveRef and the id of draft-04 are not read; the survey of the keywords jlens ignores is roadmap 0.34.
  • The packages over jlens-schema (the CLI, the language server, the WebAssembly and Java packages, the C API) load such schemas at once, as they call Schema::from_json_schema. Giving them the documents and the report is a separate item of the roadmap.

Results: the documents and the report at every end (0.33 #10)

  • One JSON form of the report, that of LoadReport: {"unresolved": [{"place", "reference", "uri", "document"}]}, document absent when the document is there without the place, and {} when every $ref was followed. 0.34 #10 added a second member, "unread": [{"place", "keyword"}], the keywords not read whose places are left unknown, and 0.35 #6 a third, "openTuples": [{"place"}], the tuples that are read and say nothing of the items after them. fixtures/uses/cases.json has, under references, a schema of two documents, its report with the other document and alone, and for two expressions what each uses and what giving the document changes; the Rust crate, the C API, the Java package, the WebAssembly package and the CLI each answer it.
  • The C API: jlens_schema_new takes a second buffer, the sources (0 for none): the JSON object {"uri": …, "documents": {uri: buffer}}, each document in a buffer of its own, named by its handle as a variable’s schema is in a service’s declarations (ADR 0023). Inlining the documents in the sources would make the host write one JSON text out of several, and a document that is not JSON would fail as the sources. jlens_schema_report replies with the report of a schema, which is kept with it. Sources not in their form fail with U2005 and the token sources.
  • Java: Schema.loader() with uri, document and load; Schema.fromJson is the load with no document. unresolved() is a list of UnresolvedRef records and missingDocuments() the documents to give. The report is read once, when the schema is made: one more call for each schema, and none after, nor after the schema is closed.
  • The WebAssembly package has no schema object: LanguageService takes the sources as its fourth argument, { uri, documents }, and schemaReport(schema, sources) gives the report of one schema. The documents serve the schemas of the variables too; uri is that of the input’s schema.
  • The CLI and the language server read files, never the network. A document is read from the file at the same relative path from the schema’s file as between the two URIs: that of the document, and the schema’s $id or else the URI of its file. So common.json beside the schema is found whether the schema has an $id on some host or none, and a document on another host, or with a query, is not read. .. is allowed: the schemas are the user’s own files, and what is read is used only as a schema. A variable’s schema, written in jlens.json, refers to files from that folder. SchemaLoader::load_asking, in jlens-schema, is the loop behind it: load, ask a function for the documents the report names, load again with those it gave, until none is new; each URI is asked for once and no more than 256, so that links between folders cannot make it endless. A chain of documents more than 64 deep still fails as a schema nested too deep.
  • What is not followed is a warning, not a failure: a line on standard error for each document not found, with the number of $refs to it, and one for each $ref to a place its document does not have; a message in the language server, once for each service it makes. --deny-warnings does not count them: they are about the schema, not the expression checked. A file that is there and is not JSON fails, as the schema’s does.
  • The size. The Windows library is 3,637,760 bytes, 16.4% over 0.32.0, against 12.2% after 0.33 #7: the recursive schemas (#8), the loader with its URI resolver (#9) and the two exports of this item. Roadmap 0.33 #12 measures the library and the JAR as released.

0026 — jlens-schema reads JSON Schema itself, into shapes, and infers its own

Status: Accepted. Recorded in 0.34, after the fact: the reader and the inference date from the first jlens-schema (October 2026), and the references grew in 0.33 (ADR 0024, ADR 0025).

Context

jlens-schema does two things with JSON Schema. It infers a schema from sample documents (Schema::infer, jlens schema infer), and it reads one, inferred, written by hand or generated by another tool, for the language service: completion, hover, the diagnostics, the type of the result and what an expression uses. Rust has mature JSON Schema crates, and ADR 0001 only covers implementing JSONata itself. So the question is whether jlens reinvents them.

What the language service needs from a schema is not what a validator gives:

  • A query without a document. The typing asks, for a path that an expression builds, which fields and which types a value can have there. No document is at hand when someone types customer. in an editor. The load therefore turns the schema into Schema, a tree of Shapes (types, fields with required or their presence, items, enum, format, ranges, descriptions, the fields an object leaves open, references by name to definitions), which Schema::shape_at and the typing walk.
  • A reading that keeps the warnings sound. A warning says that the schema does not allow something, so a keyword that allows more must be read, and one that only narrows may be left out. The schema guide classifies every keyword of JSON Schema 2020-12, the drafts before it and OpenAPI 3.0 that way (the keywords jlens reads): read, left out because it only narrows or only describes, or reported. A reported keyword ($dynamicRef, $recursiveRef, a type that names no JSON type) leaves its place unknown, and the load lists it beside the schema.
  • Combinators read as sets of values. allOf is merged into one shape. Roadmap 0.34 #11 reads anyOf and oneOf as one branch or another: a field is required only where every branch requires it, and a branch that gives no type leaves the type unknown. A validator needs neither: it checks each branch against the document.
  • A load that does not fail. A $ref that cannot be followed leaves its place unknown and is reported with its place (ADR 0025), and the load is bounded by the size of its documents, whoever wrote them.

Inference has needs of its own. It records more than the schema a GenSON-style tool writes (types, properties, required, items): the fraction of objects that had a field that is not required (x-jlens-presence), string formats, number ranges, small enumerations (x-jlens-enum-inferred), minItems: 1 for arrays never seen empty (x-jlens-min-items-inferred) and examples. It observes samples into the same Shape the load builds, so an inferred schema, written and read again, answers the same.

The crates checked

On crates.io, on 2026-11-12. “Last release” is the date of the version given.

CrateVersion, last releaseWhat it isWhy it does not serve
jsonschema0.61.2, 2026-11-12The most used validator. Compiles a schema into a Validator; validates documents, with errors and the annotations of the Output v1 format; fetches remote references, bundles and dereferences schemas, validates against meta-schemasIts questions are about a document. A compiled Validator exposes checks, not the fields and types of a place
referencing0.61.2, 2026-11-12The resolver of jsonschema, from the same repository: a Registry of documents by URI, a Resolver that looks up a reference, per-draft rules, the dynamic scope of $dynamicRef, a Retrieve trait for documents not givenIt could have served the resolution: see below
boon0.6.1, 2025-01-07A validator, drafts 4 to 2020-12; passes the JSON-Schema-Test-Suite but its optional cases; errors as a hierarchyAs jsonschema
valico4.0.0, 2023-05-13A validator and coercer, draft 7; no repository named on crates.ioAs jsonschema, and no release since 2023
jsonschema-valid0.5.2, 2023-11-08A validator, drafts 4, 6 and 7As jsonschema, and no 2019-09 or 2020-12
json_schema_ast0.6.0, 2026-11-12Builds, validates and resolves 2020-12 schemas and OpenAPI 3.1 Schema Objects, with a resolved graph that can be walked; the front end of jsoncompatThe closest to a static reader, but its README rejects the other drafts named by $schema, does not read OpenAPI 3.0’s nullable, and rejects plain-name fragments ($anchor), dynamic references, and remote ones not registered beforehand. It has no notion of a keyword that only narrows
jsonschema-schema0.2.0, 2026-03-06Typed structs for the keywords of 2020-12, with navigate_pointer, which follows $refA typed parse of the keywords, not a reading of them: what each means for a place would remain jlens’s
unbinder0.2.0, 2026-10-14Replaces each $ref by its target, bounded by depth, size and document limits; Documents lists the documents still missing and opens none; a cycle is left as $ref and listedIts output is a schema again, which jlens would still read, and a cycle left as $ref would still be jlens’s to resolve. Its $ids follow json-schema-ref-parser, counting only where the root has one or names a draft, and its README does not mention $anchor
schemars1.2.3, 2026-10-12A schema from Rust types (#[derive(JsonSchema)])The other direction
typify0.8.0, 2026-09-09 (0.10.0-alpha.3, 2026-10-14)Rust types from a schema, as source code at build timeThe other end of the same problem: its README calls JSON Schema “a constraint language designed for validation”, which it reads as one interpretation into Rust types. jlens needs the reading at run time, as data, and keeps what it cannot read unknown
genson-rs0.2.0, 2024-05-26A fast port of GenSON: a schema (draft-04 and later) inferred from documentsThe GenSON schema, without the presence, formats, ranges, enumerations and minItems above. No release since 2024
genson-core1.4.0, 2026-10-26A vendored and extended genson-rs, with normalisation to Avro and Parquet schemasAs genson-rs; its additions are for data pipelines
json-schema-profiler0.0.1, 2026-10-25Counts, at each path of a set of documents, how often a field is present and of which type, then proposes a schema under a strict or an expansive policyThe nearest to jlens’s inference, but experimental, and released after it

The options

  1. Build on a validator (jsonschema, boon). A compiled validator holds checks run against a document, and gives no way to ask what a place may hold. jlens would walk the schema’s JSON itself all the same, and carry a validator it never runs.
  2. Build on a static reading (json_schema_ast, jsonschema-schema, typify’s type space). These read a schema without a document, but each covers fewer drafts or dialects than jlens reads, or ends in Rust source. None tells a keyword that widens from one that narrows, and none leaves a place unknown and reports why. The rules of the guide’s table would be written over them all the same.
  3. Read the schema ourselves, from its JSON values, possibly taking the resolution of $ref from referencing.

Where reuse was possible: referencing

The step from the text of a $ref to its target is the same for a validator and for jlens. referencing does what decision 2 of ADR 0025 describes (base URIs from $id, anchors, JSON Pointers), and more: the rules of each draft, such as draft-04’s id, and the dynamic scope that $dynamicRef and $recursiveRef need, which jlens reports instead of reading. It is maintained and widely used. jlens kept its own resolver, uri.rs (RFC 3986, section 5.2, in about 330 lines with their tests) and the index of $ids and $anchors in the load, because:

  • The part it would replace is small, and the rest stays. What ADR 0024 and ADR 0025 decide is about the walk over the schema: the $refs that lead back to themselves, found as the strongly connected components of the graph of references, become references by name; the budget counts the values each target would copy before any is copied; the report gives the place of each $ref not followed. referencing resolves a reference given to it, so all of that would remain.
  • Its failures are not jlens’s. Its README says that it resolves every external reference eagerly, and RegistryBuilder::prepare fails when a retrieval fails. jlens loads the schema without the document, leaves each place that needs it unknown and lists them, and the CLI asks for the documents and loads again (load_asking). A Retrieve that records what it was asked and returns a placeholder could imitate that, but the placeholder would be read as a schema.
  • Its dependencies. referencing 0.61.2 brings ahash, fluent-uri, getrandom, micromap, parking_lot and percent-encoding, none of which jlens builds today: jlens-schema adds nothing to what the evaluator already depends on. The WebAssembly package, which builds jlens-schema, has a size budget, and the C API ships it in every library of the Java package.

What would change this: reading $dynamicRef and $recursiveRef instead of reporting them, or reading draft-04’s id. Their scope is what referencing already implements, and writing it again would be reinventing it. Then referencing would be weighed again, for the step from the text to the target only, under the walk, the budget and the report.

Decision

jlens-schema reads JSON Schema itself: the load walks the schema’s JSON values, resolves $ref with its own URI resolver, and builds Shapes, following the keyword classification of the schema guide. Inference is its own as well, and observes samples into the same shapes.

jlens does not validate documents against a schema. An application that needs validation uses a validator crate beside jlens, which neither competes with it nor wraps it.

Consequences

  • jlens owns the classification of the keywords, and keeps it current: a new draft or dialect is a change to the guide’s table and to the load, and until then its new keywords are not read.
  • The resolution of $ref, $id and $anchor is tested by jlens’s own tests only. The official JSON-Schema-Test-Suite could test it: the schemas of its reference cases (such as ref.json, refRemote.json and anchor.json), with the documents of its remotes folder given by URI, should load with every $ref followed, and the shape of a place should hold its valid documents. This is a possibility, not a plan.
  • jlens-schema has no dependency on a validator or a resolver: its dependencies are those of the evaluator.
  • When referencing gains what jlens would otherwise write (above), this ADR is to be revisited, not extended in place: a later ADR supersedes it.