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

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.