From 9bf8d3f1bfd561951dbe00919974ea51000a3110 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:21:05 +0000 Subject: [PATCH 1/7] Issue #178: document interpreted and compiled JsonPath engines (docs first) Markdown-Driven-Development: describes the two-engine contract (interpreted = JDK 21+ AST walker, compiled = JDK 24+ ClassFile API emitting Java 21 bytecode in the jtd-codegen style) before implementation, including the ahead-of-time compileBytes tooling path and the parity guarantee backed by JsonPathCompilerParityTest. To verify: read json-java21-jsonpath/README.md section 'Two Engines'. --- json-java21-jsonpath/AGENTS.md | 13 ++++++++-- json-java21-jsonpath/README.md | 41 +++++++++++++++++++++++++++++++ json-java21-jtd-codegen/README.md | 4 +++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/json-java21-jsonpath/AGENTS.md b/json-java21-jsonpath/AGENTS.md index b8d9ba71..2990fa5b 100644 --- a/json-java21-jsonpath/AGENTS.md +++ b/json-java21-jsonpath/AGENTS.md @@ -6,12 +6,21 @@ This file is for contributor/agent operational notes. Read `json-java21-jsonpath - The `$(command -v mvnd || command -v mvn || command -v ./mvnw)` wrapper is for local developer speed only; do not put it in user-facing docs. Stable code entry points: -- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java` +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java` (public sealed interface; `parse` = interpreted engine, `compile` = compiled engine) +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java` (AST-walking interpreter) +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCompiled.java` (compiled engine facade) +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathExecutor.java` (package-private functional interface implemented by generated classes) - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathParser.java` - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathAst.java` - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathParseException.java` - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathStreams.java` +Compiled engine (JDK 24+ only; the Maven profile `jsonpath-codegen` activates on JDK 24+ and adds `src/main/codegen/java` plus `src/test/codegen/java`): +- `json-java21-jsonpath/src/main/codegen/java/json/java21/jsonpath/JsonPathCodegen.java` (ClassFile API, JEP 484; emits `ClassFile.JAVA_21_VERSION` / version 65 bytecode) +- `json-java21-jsonpath/src/main/codegen/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java` (AST-to-bytecode emitter) +- `json-java21-jsonpath/src/test/codegen/java/json/java21/jsonpath/JsonPathCompilerParityTest.java` (interpreted == generated parity over the existing test corpus) + When changing syntax/behavior: - Update `JsonPathAst` + `JsonPathParser` + `JsonPath` together. -- Add parser + evaluation tests; new tests should extend `JsonPathLoggingConfig`. +- Mirror the change in `JsonPathBytecodeEmitter` (and `JsonPathHelpers` when shared evaluation logic moves); the parity test suite guards the interpreted/generated contract. +- Add parser + evaluation tests; new tests should extend `JsonPathLoggingConfig`; add a matching parity entry for any new operator. diff --git a/json-java21-jsonpath/README.md b/json-java21-jsonpath/README.md index 5c2af453..99803c23 100644 --- a/json-java21-jsonpath/README.md +++ b/json-java21-jsonpath/README.md @@ -60,6 +60,47 @@ This implementation follows Goessner-style JSONPath operators, including: - `[?(@.prop)]` and `[?(@.prop op value)]` basic filters - `[(@.length-1)]` limited script support +## Two Engines: Interpreted and Compiled + +This module ships the same JsonPath language with two interchangeable engines behind one API: + +| Engine | Class | Availability | Mechanism | +|---|---|---|---| +| Interpreted | `JsonPath.parse(...)` result | JDK 21+ (default) | walks the `JsonPathAst` tree per query | +| Compiled | `JsonPath.compile(...)` result | JDK 24+ runtime | bytecode generated with the JDK 24 ClassFile API (JEP 484), targeting Java 21 bytecode (`ClassFile.JAVA_21_VERSION`, class file version 65) | + +Both engines implement the same `JsonPath` public surface, so callers can hand either one to the same API. The compiled engine mirrors the approach already shipped for JTD validation in [`json-java21-jtd-codegen`](../json-java21-jtd-codegen/README.md) (`JtdCodegen` / `JtdValidator.compileGenerated`). + +### Using the Compiled Engine + +```java +// Parse once, compile for the best repeated-query performance +JsonPath path = JsonPath.parse("$.store.book[*].author"); + +for (JsonValue doc : documents) { + List results = JsonPath.compile(path).query(doc); + // process results... +} +``` + +Compiling an already-compiled path returns the same instance (compilation is idempotent). The compiled engine keeps the original path text (`toString()`) and the AST (`ast()`), so a compiled path is a drop-in replacement anywhere an interpreted path is accepted. + +### Runtime Requirements + +- **Interpreted engine**: JDK 21+; no dependency on the ClassFile API; unchanged semantics. +- **Compiled engine**: generating classes requires a JDK 24+ runtime (`java.lang.classfile`, JEP 484). Calling `compile()` on JDK 21 or earlier fails with a `NoClassDefFoundError`; use the interpreted engine there. The generated classes are Java 21 bytecode and only need Java 21 API surface at query time. +- **Ahead-of-time (build-time) tooling**: `JsonPathCodegen.compileBytes(...)` returns the raw generated classfile bytes without loading them, in the same style as `JtdCodegen.compileBytes(...)` for `jtd2jar`-style standalone JAR builds. + +### Parity Guarantee + +Compiled and interpreted engines produce identical results, in the same order, for every expression in the supported-syntax table above. The module's parity test suite (`JsonPathCompilerParityTest`) reuses the existing test corpus and asserts `compiled.query(doc)` equals `interpreted.query(doc)` element-for-element for both engines. + +### Supported Features in Compiled Mode + +All supported operators are supported by the compiled engine: +- property access (dot and bracket), array indices (including negative), slices +- wildcards, recursive descent (`$..name`, `$..*`), unions, filters with comparisons and logical operators, and the limited `[(@.length-1)]` script expression + ## Stream-Based Functions (Aggregations) Some JsonPath implementations include aggregation functions such as `$.numbers.avg()`. diff --git a/json-java21-jtd-codegen/README.md b/json-java21-jtd-codegen/README.md index 0036a123..01a43660 100644 --- a/json-java21-jtd-codegen/README.md +++ b/json-java21-jtd-codegen/README.md @@ -10,6 +10,10 @@ For **infrequent validation** (config loading, startup checks, one-off validatio > **Future note**: `java.util.json` has entered the JDK incubator (`jdk.incubator.json`). Once the API stabilises in the JDK itself, generated bytecode validators can depend directly on future JDK classes rather than this backport, making them even more efficient with zero library overhead. +## Same Pattern for Other Engines + +The compiled-engine blueprint in this module (emitters + `Descriptors` + `ClassFile.JAVA_21_VERSION` output + `Lookup.defineClass`) is reused by the JsonPath module's compiled engine: `JsonPath.parse(...)` gives the interpreted engine (always available, JDK 21+) and `JsonPath.compile(...)` gives the bytecode-generated engine (JDK 24+ runtime, Java 21 bytecode). See [`json-java21-jsonpath`](../json-java21-jsonpath/README.md#two-engines-interpreted-and-compiled) for the two-engine contract and its parity test suite. + ## Requirements - **Build**: JDK 24+ (uses `ClassFile` API, JEP 484) From 9d8a1586d1dca08e9419e82f4a66eafe5d843ab4 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:22:38 +0000 Subject: [PATCH 2/7] Issue #178: refactor JsonPath into a sealed interface over the interpreted engine Salvaged from the sealed-interface split of the Issue #128 work, reworked onto the current jdk.incubator API: 'JsonPath' is now a public sealed interface permitting 'JsonPathInterpreted' (the unchanged AST-walking engine, package private, JDK 21+, no ClassFile API dependency) and 'JsonPathCompiled'. The compiled-engine facade and its package-private 'JsonPathExecutor' land here so the seal is complete; their construction is wired up by the ClassFile API codegen in the following commit. All 100 existing JsonPath tests pass. To verify: /opt/homebrew/bin/mvnd -pl json-java21-jsonpath test -Djava.util.logging.ConsoleHandler.level=INFO (100 tests green). --- .../java/json/java21/jsonpath/JsonPath.java | 571 +----------------- .../java21/jsonpath/JsonPathCompiled.java | 59 ++ .../java21/jsonpath/JsonPathExecutor.java | 21 + .../java21/jsonpath/JsonPathInterpreted.java | 570 +++++++++++++++++ 4 files changed, 678 insertions(+), 543 deletions(-) create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCompiled.java create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathExecutor.java create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java index c58702b6..18e9b630 100644 --- a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPath.java @@ -2,7 +2,6 @@ import jdk.incubator.java.util.json.*; -import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.logging.Logger; @@ -10,6 +9,11 @@ /// JsonPath query evaluator for JSON documents. /// Parses JsonPath expressions and evaluates them against JsonValue instances. /// +/// The module provides two engines behind this one API: +/// - the interpreted engine (default), which walks the JSONPath AST per query, available on JDK 21+; +/// - the compiled engine, whose executors are bytecode generated by the JDK 24+ ClassFile API +/// targeting Java 21 bytecode; obtain one via {@code JsonPathCodegen} on a JDK 24+ runtime. +/// /// Usage examples: /// ```java /// // Fluent API @@ -22,47 +26,32 @@ /// ``` /// /// Based on the JSONPath specification from [...](https://goessner.net/articles/JsonPath/) -public final class JsonPath { - - private static final Logger LOG = Logger.getLogger(JsonPath.class.getName()); - - private final JsonPathAst.Root ast; +public sealed interface JsonPath permits JsonPathInterpreted, JsonPathCompiled { - private JsonPath(JsonPathAst.Root ast) { - this.ast = ast; - } + /// Shared JUL logger for the JsonPath engine factories. + Logger LOG = Logger.getLogger(JsonPath.class.getName()); - /// Parses a JsonPath expression and returns a compiled JsonPath for reuse. + /// Parses a JsonPath expression and returns an interpreted JsonPath for reuse. /// @param path the JsonPath expression - /// @return a compiled JsonPath that can be used to select from multiple documents + /// @return an interpreted JsonPath that can be used to select from multiple documents /// @throws NullPointerException if path is null /// @throws JsonPathParseException if the path is invalid - public static JsonPath parse(String path) { + static JsonPath parse(String path) { Objects.requireNonNull(path, "path must not be null"); LOG.fine(() -> "Parsing path: " + path); final var ast = JsonPathParser.parse(path); - return new JsonPath(ast); + return new JsonPathInterpreted(ast); } /// Queries matching values from a JSON document. /// - /// Instance API: compile once via `parse(String)`, then call `query(JsonValue)` for each already-parsed + /// Instance API: parse once via `parse(String)`, then call `query(JsonValue)` for each already-parsed /// JSON document. /// /// @param json the JSON document to query /// @return a list of matching JsonValue instances (maybe empty) /// @throws NullPointerException if JSON is null - public List query(JsonValue json) { - Objects.requireNonNull(json, "json must not be null"); - LOG.fine(() -> "Querying document with path: " + this); - return evaluate(ast, json); - } - - /// Reconstructs the JsonPath expression from the AST. - @Override - public String toString() { - return reconstruct(ast); - } + List query(JsonValue json); /// Evaluates a compiled JsonPath against a JSON document. /// @param path a compiled JsonPath (typically cached) @@ -89,528 +78,24 @@ public static List query(String path, JsonValue json) { return parse(path).query(json); } - /// Evaluates a pre-parsed JsonPath AST against a JSON document. - /// @param ast the parsed JsonPath AST - /// @param json the JSON document to query - /// @return a list of matching JsonValue instances (maybe empty) - static List evaluate(JsonPathAst.Root ast, JsonValue json) { - Objects.requireNonNull(ast, "ast must not be null"); - Objects.requireNonNull(json, "json must not be null"); - - final var results = new ArrayList(); - evaluateSegments(ast.segments(), 0, json, json, results); - return results; - } - - private static void evaluateSegments( - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - // If we've processed all segments, current is a match - if (index >= segments.size()) { - results.add(current); - return; - } - - final var segment = segments.get(index); - LOG.finer(() -> "Evaluating segment " + index + ": " + segment); - - switch (segment) { - case JsonPathAst.PropertyAccess prop -> evaluatePropertyAccess(prop, segments, index, current, root, results); - case JsonPathAst.ArrayIndex arr -> evaluateArrayIndex(arr, segments, index, current, root, results); - case JsonPathAst.ArraySlice slice -> evaluateArraySlice(slice, segments, index, current, root, results); - case JsonPathAst.Wildcard ignored -> evaluateWildcard(segments, index, current, root, results); - case JsonPathAst.RecursiveDescent desc -> evaluateRecursiveDescent(desc, segments, index, current, root, results); - case JsonPathAst.Filter filter -> evaluateFilter(filter, segments, index, current, root, results); - case JsonPathAst.Union union -> evaluateUnion(union, segments, index, current, root, results); - case JsonPathAst.ScriptExpression script -> evaluateScriptExpression(script, segments, index, current, root, results); - } + /// Returns true if this JsonPath is the AST-walking interpreter engine. + /// @return true when this instance is the interpreted engine + default boolean isInterpreted() { + return this instanceof JsonPathInterpreted; } - private static void evaluatePropertyAccess( - JsonPathAst.PropertyAccess prop, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonObject obj) { - final var value = obj.asMap().get(prop.name()); - if (value != null) { - evaluateSegments(segments, index + 1, value, root, results); - } - } + /// Returns true if this JsonPath is backed by a bytecode-generated executor. + /// @return true when this instance is the compiled engine + default boolean isCompiled() { + return this instanceof JsonPathCompiled; } - private static void evaluateArrayIndex( - JsonPathAst.ArrayIndex arr, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonArray array) { - final var elements = array.asList(); - int idx = arr.index(); - - // Handle negative indices (from end) - if (idx < 0) { - idx = elements.size() + idx; - } - - if (idx >= 0 && idx < elements.size()) { - evaluateSegments(segments, index + 1, elements.get(idx), root, results); - } - } - } - - private static void evaluateArraySlice( - JsonPathAst.ArraySlice slice, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonArray array) { - final var elements = array.asList(); - final int size = elements.size(); - - final int step = slice.step() != null ? slice.step() : 1; - - if (step == 0) { - return; // Invalid step - } - - if (step > 0) { - int start = slice.start() != null ? normalizeIndex(slice.start(), size) : 0; - int end = slice.end() != null ? normalizeIndex(slice.end(), size) : size; - - start = Math.max(0, Math.min(start, size)); - end = Math.max(0, Math.min(end, size)); - - for (int i = start; i < end; i += step) { - evaluateSegments(segments, index + 1, elements.get(i), root, results); - } - } else { - int start = slice.start() != null ? normalizeIndex(slice.start(), size) : size - 1; - final int end = slice.end() != null ? normalizeIndex(slice.end(), size) : -1; - - start = Math.max(0, Math.min(start, size - 1)); - - for (int i = start; i > end; i += step) { - evaluateSegments(segments, index + 1, elements.get(i), root, results); - } - } - } - } - - private static int normalizeIndex(int index, int size) { - if (index < 0) { - return size + index; - } - return index; - } - - private static void evaluateWildcard( - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonObject obj) { - for (final var value : obj.asMap().values()) { - evaluateSegments(segments, index + 1, value, root, results); - } - } else if (current instanceof JsonArray array) { - for (final var element : array.asList()) { - evaluateSegments(segments, index + 1, element, root, results); - } - } - } - - private static void evaluateRecursiveDescent( - JsonPathAst.RecursiveDescent desc, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - // First, try matching the target at current level - evaluateTargetSegment(desc.target(), segments, index, current, root, results); - - // Then recurse into children - if (current instanceof JsonObject obj) { - for (final var value : obj.asMap().values()) { - evaluateRecursiveDescent(desc, segments, index, value, root, results); - } - } else if (current instanceof JsonArray array) { - for (final var element : array.asList()) { - evaluateRecursiveDescent(desc, segments, index, element, root, results); - } - } - } - - private static void evaluateTargetSegment( - JsonPathAst.Segment target, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - switch (target) { - case JsonPathAst.PropertyAccess prop -> { - if (current instanceof JsonObject obj) { - final var value = obj.asMap().get(prop.name()); - if (value != null) { - evaluateSegments(segments, index + 1, value, root, results); - } - } - } - case JsonPathAst.Wildcard ignored -> { - if (current instanceof JsonObject obj) { - for (final var value : obj.asMap().values()) { - evaluateSegments(segments, index + 1, value, root, results); - } - } else if (current instanceof JsonArray array) { - for (final var element : array.asList()) { - evaluateSegments(segments, index + 1, element, root, results); - } - } - } - case JsonPathAst.ArrayIndex arr -> { - if (current instanceof JsonArray array) { - final var elements = array.asList(); - int idx = arr.index(); - if (idx < 0) idx = elements.size() + idx; - if (idx >= 0 && idx < elements.size()) { - evaluateSegments(segments, index + 1, elements.get(idx), root, results); - } - } - } - default -> // Other segment types in recursive descent context - LOG.finer(() -> "Unsupported target in recursive descent: " + target); - } - } - - private static void evaluateFilter( - JsonPathAst.Filter filter, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonArray array) { - for (final var element : array.asList()) { - if (matchesFilter(filter.expression(), element)) { - evaluateSegments(segments, index + 1, element, root, results); - } - } - } - } - - private static boolean matchesFilter(JsonPathAst.FilterExpression expr, JsonValue current) { - return switch (expr) { - case JsonPathAst.ExistsFilter exists -> { - final var value = resolvePropertyPath(exists.path(), current); - yield value != null; - } - case JsonPathAst.ComparisonFilter comp -> { - final var leftValue = resolveFilterExpression(comp.left(), current); - final var rightValue = resolveFilterExpression(comp.right(), current); - yield compareValues(leftValue, comp.op(), rightValue); - } - case JsonPathAst.LogicalFilter logical -> { - final var leftMatch = matchesFilter(logical.left(), current); - yield switch (logical.op()) { - case AND -> leftMatch && matchesFilter(logical.right(), current); - case OR -> leftMatch || matchesFilter(logical.right(), current); - case NOT -> !leftMatch; - }; - } - case JsonPathAst.CurrentNode ignored1 -> true; - case JsonPathAst.PropertyPath path -> resolvePropertyPath(path, current) != null; - case JsonPathAst.LiteralValue ignored -> true; - }; - } - - private static Object resolveFilterExpression(JsonPathAst.FilterExpression expr, JsonValue current) { - return switch (expr) { - case JsonPathAst.PropertyPath path -> { - final var value = resolvePropertyPath(path, current); - yield jsonValueToComparable(value); - } - case JsonPathAst.LiteralValue lit -> lit.value(); - case JsonPathAst.CurrentNode ignored -> jsonValueToComparable(current); - default -> null; - }; - } - - private static JsonValue resolvePropertyPath(JsonPathAst.PropertyPath path, JsonValue current) { - JsonValue value = current; - for (final var prop : path.properties()) { - if (value instanceof JsonObject obj) { - value = obj.asMap().get(prop); - if (value == null) { - return null; - } - } else { - return null; - } - } - return value; - } - - private static Object jsonValueToComparable(JsonValue value) { - if (value == null) return null; - return switch (value) { - case JsonString s -> s.asString(); - case JsonNumber n -> n.asDouble(); - case JsonBoolean b -> b.asBoolean(); - case JsonNull ignored -> null; - default -> value; - }; - } - - @SuppressWarnings("unchecked") - private static boolean compareValues(Object left, JsonPathAst.ComparisonOp op, Object right) { - if (left == null || right == null) { - return switch (op) { - case EQ -> left == right; - case NE -> left != right; - default -> false; - }; - } - - // Try numeric comparison - switch (left) { - case Number leftNum when right instanceof Number rightNum -> { - final double l = leftNum.doubleValue(); - final double r = rightNum.doubleValue(); - return switch (op) { - case EQ -> l == r; - case NE -> l != r; - case LT -> l < r; - case LE -> l <= r; - case GT -> l > r; - case GE -> l >= r; - }; - } - - - // String comparison - case String ignored when right instanceof String -> { - @SuppressWarnings("rawtypes") final int cmp = ((Comparable) left).compareTo(right); - return switch (op) { - case EQ -> cmp == 0; - case NE -> cmp != 0; - case LT -> cmp < 0; - case LE -> cmp <= 0; - case GT -> cmp > 0; - case GE -> cmp >= 0; - }; - } - - - // Boolean comparison - case Boolean ignored when right instanceof Boolean -> { - return switch (op) { - case EQ -> left.equals(right); - case NE -> !left.equals(right); - default -> false; - }; - } - default -> { - } - } - - // Fallback equality - return switch (op) { - case EQ -> left.equals(right); - case NE -> !left.equals(right); - default -> false; + /// Returns the AST for this JsonPath. + /// @return the parsed AST root shared by both engines + default JsonPathAst.Root ast() { + return switch (this) { + case JsonPathInterpreted interpreted -> interpreted.ast(); + case JsonPathCompiled compiled -> compiled.ast(); }; } - - private static void evaluateUnion( - JsonPathAst.Union union, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - for (final var selector : union.selectors()) { - switch (selector) { - case JsonPathAst.ArrayIndex arr -> evaluateArrayIndex(arr, segments, index, current, root, results); - case JsonPathAst.PropertyAccess prop -> evaluatePropertyAccess(prop, segments, index, current, root, results); - default -> LOG.finer(() -> "Unsupported selector in union: " + selector); - } - } - } - - private static void evaluateScriptExpression( - JsonPathAst.ScriptExpression script, - List segments, - int index, - JsonValue current, - JsonValue root, - List results) { - - if (current instanceof JsonArray array) { - // Simple support for @.length-1 pattern - final var scriptText = script.script().trim(); - if (scriptText.equals("@.length-1")) { - final int lastIndex = array.asList().size() - 1; - if (lastIndex >= 0) { - evaluateSegments(segments, index + 1, array.asList().get(lastIndex), root, results); - } - } else { - LOG.warning(() -> "Unsupported script expression: " + scriptText); - } - } - } - - private static String reconstruct(JsonPathAst.Root root) { - final var sb = new StringBuilder("$"); - for (final var segment : root.segments()) { - appendSegment(sb, segment); - } - return sb.toString(); - } - - private static void appendSegment(StringBuilder sb, JsonPathAst.Segment segment) { - switch (segment) { - case JsonPathAst.PropertyAccess prop -> { - if (isSimpleIdentifier(prop.name())) { - sb.append(".").append(prop.name()); - } else { - sb.append("['").append(escape(prop.name())).append("']"); - } - } - case JsonPathAst.ArrayIndex arr -> sb.append("[").append(arr.index()).append("]"); - case JsonPathAst.ArraySlice slice -> { - sb.append("["); - if (slice.start() != null) sb.append(slice.start()); - sb.append(":"); - if (slice.end() != null) sb.append(slice.end()); - if (slice.step() != null) sb.append(":").append(slice.step()); - sb.append("]"); - } - case JsonPathAst.Wildcard ignored -> sb.append(".*"); - case JsonPathAst.RecursiveDescent desc -> { - sb.append(".."); - // RecursiveDescent target is usually PropertyAccess or Wildcard, - // but can be other things in theory. - // If target is PropertyAccess("foo"), append "foo". - // If target is Wildcard, append "*". - // Our AST structure wraps the target segment. - // We need to handle how it's appended. - // appendSegment prepends "." or "[" usually. - // But ".." replaces the dot. - // Let special case the target printing. - appendRecursiveTarget(sb, desc.target()); - } - case JsonPathAst.Filter filter -> { - sb.append("[?("); - appendFilterExpression(sb, filter.expression()); - sb.append(")]"); - } - case JsonPathAst.Union union -> { - sb.append("["); - final var selectors = union.selectors(); - for (int i = 0; i < selectors.size(); i++) { - if (i > 0) sb.append(","); - appendUnionSelector(sb, selectors.get(i)); - } - sb.append("]"); - } - case JsonPathAst.ScriptExpression script -> sb.append("[(").append(script.script()).append(")]"); - } - } - - private static void appendRecursiveTarget(StringBuilder sb, JsonPathAst.Segment target) { - if (target instanceof JsonPathAst.PropertyAccess(String name)) { - sb.append(name); // ..name - } else if (target instanceof JsonPathAst.Wildcard) { - sb.append("*"); // ..* - } else { - // Fallback for other types if they ever occur in recursive position - appendSegment(sb, target); - } - } - - private static void appendUnionSelector(StringBuilder sb, JsonPathAst.Segment selector) { - if (selector instanceof JsonPathAst.PropertyAccess(String name)) { - sb.append("'").append(escape(name)).append("'"); - } else if (selector instanceof JsonPathAst.ArrayIndex(int index)) { - sb.append(index); - } else { - // Fallback - appendSegment(sb, selector); - } - } - - private static void appendFilterExpression(StringBuilder sb, JsonPathAst.FilterExpression expr) { - switch (expr) { - case JsonPathAst.ExistsFilter exists -> appendFilterExpression(sb, exists.path()); // Should print the path - case JsonPathAst.ComparisonFilter comp -> { - appendFilterExpression(sb, comp.left()); - sb.append(comp.op().symbol()); - appendFilterExpression(sb, comp.right()); - } - case JsonPathAst.LogicalFilter logical -> { - if (logical.op() == JsonPathAst.LogicalOp.NOT) { - sb.append("!"); - appendFilterExpression(sb, logical.left()); - } else { - sb.append("("); - appendFilterExpression(sb, logical.left()); - sb.append(" ").append(logical.op().symbol()).append(" "); - appendFilterExpression(sb, logical.right()); - sb.append(")"); - } - } - case JsonPathAst.CurrentNode ignored -> sb.append("@"); - case JsonPathAst.PropertyPath path -> { - sb.append("@"); - for (String p : path.properties()) { - if (isSimpleIdentifier(p)) { - sb.append(".").append(p); - } else { - sb.append("['").append(escape(p)).append("']"); - } - } - } - case JsonPathAst.LiteralValue lit -> { - if (lit.value() instanceof String s) { - sb.append("'").append(escape(s)).append("'"); - } else { - sb.append(lit.value()); - } - } - } - } - - private static boolean isSimpleIdentifier(String name) { - if (name.isEmpty()) return false; - if (!Character.isJavaIdentifierStart(name.charAt(0))) return false; - for (int i = 1; i < name.length(); i++) { - if (!Character.isJavaIdentifierPart(name.charAt(i))) return false; - } - return true; - } - - private static String escape(String s) { - return s.replace("'", "\\'"); - } } diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCompiled.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCompiled.java new file mode 100644 index 00000000..97874379 --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCompiled.java @@ -0,0 +1,59 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.JsonValue; + +import java.util.List; +import java.util.Objects; +import java.util.logging.Logger; + +/// Bytecode-backed implementation of [JsonPath]. +/// +/// Instances are produced by the compiled engine only: `JsonPathCodegen` (JDK 24+) +/// generates a Java 21 classfile implementing [JsonPathExecutor] and wraps it here. +/// The resulting path implements the same [JsonPath] public surface as the +/// interpreted engine, so callers can hand either to the same API. +final class JsonPathCompiled implements JsonPath { + + private static final Logger LOG = Logger.getLogger(JsonPathCompiled.class.getName()); + + private final JsonPathAst.Root astRoot; + private final JsonPathExecutor executor; + private final String originalPath; + + JsonPathCompiled(JsonPathAst.Root ast, JsonPathExecutor executor, String originalPath) { + this.astRoot = Objects.requireNonNull(ast, "ast must not be null"); + this.executor = Objects.requireNonNull(executor, "executor must not be null"); + this.originalPath = Objects.requireNonNull(originalPath, "originalPath must not be null"); + } + + /// Returns the AST shared by both engines for this compiled JsonPath. + /// @return the parsed AST root + @Override + public JsonPathAst.Root ast() { + return astRoot; + } + + /// Exposes the underlying generated executor for parity tests and diagnostics. + /// @return the bytecode-generated executor + JsonPathExecutor executor() { + return executor; + } + + /// The original path text that was compiled, preserved for diagnostics. + /// @return the original JsonPath expression + String originalPath() { + return originalPath; + } + + @Override + public List query(JsonValue json) { + Objects.requireNonNull(json, "json must not be null"); + LOG.fine(() -> "Querying document with compiled path: " + originalPath); + return executor.execute(json, json); + } + + @Override + public String toString() { + return originalPath; + } +} diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathExecutor.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathExecutor.java new file mode 100644 index 00000000..70d0ecc3 --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathExecutor.java @@ -0,0 +1,21 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.JsonValue; + +import java.util.List; + +/// Functional interface implemented by the bytecode-generated JsonPath executors. +/// +/// The compiled engine's generated class (emitted by `JsonPathCodegen` with the JDK 24+ +/// ClassFile API targeting Java 21 bytecode) implements this interface. It is package-private +/// by design: generated classes are always defined in the `json.java21.jsonpath` runtime +/// package, so the interface can stay internal to the module. +@FunctionalInterface +interface JsonPathExecutor { + + /// Executes the compiled JsonPath query against a JSON document. + /// @param current the current node being evaluated + /// @param root the root document (for `$` references) + /// @return a list of matching JsonValue instances (maybe empty) + List execute(JsonValue current, JsonValue root); +} diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java new file mode 100644 index 00000000..265dcccb --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java @@ -0,0 +1,570 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.logging.Logger; + +/// AST-walking interpreter implementation of [JsonPath]. +/// Parses JsonPath expressions and evaluates them against JsonValue instances by walking the AST. +/// +/// This is the default engine returned by {@code JsonPath.parse(String)}; it is available +/// on JDK 21+ and has no dependency on the ClassFile API. For the bytecode-generated +/// engine, see {@code JsonPathCodegen} (JDK 24+). +final class JsonPathInterpreted implements JsonPath { + + private static final Logger LOG = Logger.getLogger(JsonPathInterpreted.class.getName()); + + private final JsonPathAst.Root astRoot; + + JsonPathInterpreted(JsonPathAst.Root ast) { + this.astRoot = ast; + } + + /// Returns the AST for this interpreted JsonPath. + /// @return the parsed AST root + @Override + public JsonPathAst.Root ast() { + return astRoot; + } + + @Override + public List query(JsonValue json) { + Objects.requireNonNull(json, "json must not be null"); + LOG.fine(() -> "Querying document with path: " + this); + return evaluate(astRoot, json); + } + + /// Reconstructs the JsonPath expression from the AST. + @Override + public String toString() { + return reconstruct(astRoot); + } + + /// Evaluates a pre-parsed JsonPath AST against a JSON document. + /// @param ast the parsed JsonPath AST + /// @param json the JSON document to query + /// @return a list of matching JsonValue instances (maybe empty) + static List evaluate(JsonPathAst.Root ast, JsonValue json) { + Objects.requireNonNull(ast, "ast must not be null"); + Objects.requireNonNull(json, "json must not be null"); + + final var results = new ArrayList(); + evaluateSegments(ast.segments(), 0, json, json, results); + return results; + } + + private static void evaluateSegments( + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + // If we've processed all segments, current is a match + if (index >= segments.size()) { + results.add(current); + return; + } + + final var segment = segments.get(index); + LOG.finer(() -> "Evaluating segment " + index + ": " + segment); + + switch (segment) { + case JsonPathAst.PropertyAccess prop -> evaluatePropertyAccess(prop, segments, index, current, root, results); + case JsonPathAst.ArrayIndex arr -> evaluateArrayIndex(arr, segments, index, current, root, results); + case JsonPathAst.ArraySlice slice -> evaluateArraySlice(slice, segments, index, current, root, results); + case JsonPathAst.Wildcard ignored -> evaluateWildcard(segments, index, current, root, results); + case JsonPathAst.RecursiveDescent desc -> evaluateRecursiveDescent(desc, segments, index, current, root, results); + case JsonPathAst.Filter filter -> evaluateFilter(filter, segments, index, current, root, results); + case JsonPathAst.Union union -> evaluateUnion(union, segments, index, current, root, results); + case JsonPathAst.ScriptExpression script -> evaluateScriptExpression(script, segments, index, current, root, results); + } + } + + private static void evaluatePropertyAccess( + JsonPathAst.PropertyAccess prop, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonObject obj) { + final var value = obj.asMap().get(prop.name()); + if (value != null) { + evaluateSegments(segments, index + 1, value, root, results); + } + } + } + + private static void evaluateArrayIndex( + JsonPathAst.ArrayIndex arr, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonArray array) { + final var elements = array.asList(); + int idx = arr.index(); + + // Handle negative indices (from end) + if (idx < 0) { + idx = elements.size() + idx; + } + + if (idx >= 0 && idx < elements.size()) { + evaluateSegments(segments, index + 1, elements.get(idx), root, results); + } + } + } + + private static void evaluateArraySlice( + JsonPathAst.ArraySlice slice, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonArray array) { + final var elements = array.asList(); + final int size = elements.size(); + + final int step = slice.step() != null ? slice.step() : 1; + + if (step == 0) { + return; // Invalid step + } + + if (step > 0) { + int start = slice.start() != null ? normalizeIndex(slice.start(), size) : 0; + int end = slice.end() != null ? normalizeIndex(slice.end(), size) : size; + + start = Math.max(0, Math.min(start, size)); + end = Math.max(0, Math.min(end, size)); + + for (int i = start; i < end; i += step) { + evaluateSegments(segments, index + 1, elements.get(i), root, results); + } + } else { + int start = slice.start() != null ? normalizeIndex(slice.start(), size) : size - 1; + final int end = slice.end() != null ? normalizeIndex(slice.end(), size) : -1; + + start = Math.max(0, Math.min(start, size - 1)); + + for (int i = start; i > end; i += step) { + evaluateSegments(segments, index + 1, elements.get(i), root, results); + } + } + } + } + + private static int normalizeIndex(int index, int size) { + if (index < 0) { + return size + index; + } + return index; + } + + private static void evaluateWildcard( + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonObject obj) { + for (final var value : obj.asMap().values()) { + evaluateSegments(segments, index + 1, value, root, results); + } + } else if (current instanceof JsonArray array) { + for (final var element : array.asList()) { + evaluateSegments(segments, index + 1, element, root, results); + } + } + } + + private static void evaluateRecursiveDescent( + JsonPathAst.RecursiveDescent desc, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + // First, try matching the target at current level + evaluateTargetSegment(desc.target(), segments, index, current, root, results); + + // Then recurse into children + if (current instanceof JsonObject obj) { + for (final var value : obj.asMap().values()) { + evaluateRecursiveDescent(desc, segments, index, value, root, results); + } + } else if (current instanceof JsonArray array) { + for (final var element : array.asList()) { + evaluateRecursiveDescent(desc, segments, index, element, root, results); + } + } + } + + private static void evaluateTargetSegment( + JsonPathAst.Segment target, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + switch (target) { + case JsonPathAst.PropertyAccess prop -> { + if (current instanceof JsonObject obj) { + final var value = obj.asMap().get(prop.name()); + if (value != null) { + evaluateSegments(segments, index + 1, value, root, results); + } + } + } + case JsonPathAst.Wildcard ignored -> { + if (current instanceof JsonObject obj) { + for (final var value : obj.asMap().values()) { + evaluateSegments(segments, index + 1, value, root, results); + } + } else if (current instanceof JsonArray array) { + for (final var element : array.asList()) { + evaluateSegments(segments, index + 1, element, root, results); + } + } + } + case JsonPathAst.ArrayIndex arr -> { + if (current instanceof JsonArray array) { + final var elements = array.asList(); + int idx = arr.index(); + if (idx < 0) idx = elements.size() + idx; + if (idx >= 0 && idx < elements.size()) { + evaluateSegments(segments, index + 1, elements.get(idx), root, results); + } + } + } + default -> // Other segment types in recursive descent context + LOG.finer(() -> "Unsupported target in recursive descent: " + target); + } + } + + private static void evaluateFilter( + JsonPathAst.Filter filter, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonArray array) { + for (final var element : array.asList()) { + if (matchesFilter(filter.expression(), element)) { + evaluateSegments(segments, index + 1, element, root, results); + } + } + } + } + + private static boolean matchesFilter(JsonPathAst.FilterExpression expr, JsonValue current) { + return switch (expr) { + case JsonPathAst.ExistsFilter exists -> { + final var value = resolvePropertyPath(exists.path(), current); + yield value != null; + } + case JsonPathAst.ComparisonFilter comp -> { + final var leftValue = resolveFilterExpression(comp.left(), current); + final var rightValue = resolveFilterExpression(comp.right(), current); + yield compareValues(leftValue, comp.op(), rightValue); + } + case JsonPathAst.LogicalFilter logical -> { + final var leftMatch = matchesFilter(logical.left(), current); + yield switch (logical.op()) { + case AND -> leftMatch && matchesFilter(logical.right(), current); + case OR -> leftMatch || matchesFilter(logical.right(), current); + case NOT -> !leftMatch; + }; + } + case JsonPathAst.CurrentNode ignored1 -> true; + case JsonPathAst.PropertyPath path -> resolvePropertyPath(path, current) != null; + case JsonPathAst.LiteralValue ignored -> true; + }; + } + + private static Object resolveFilterExpression(JsonPathAst.FilterExpression expr, JsonValue current) { + return switch (expr) { + case JsonPathAst.PropertyPath path -> { + final var value = resolvePropertyPath(path, current); + yield jsonValueToComparable(value); + } + case JsonPathAst.LiteralValue lit -> lit.value(); + case JsonPathAst.CurrentNode ignored -> jsonValueToComparable(current); + default -> null; + }; + } + + private static JsonValue resolvePropertyPath(JsonPathAst.PropertyPath path, JsonValue current) { + JsonValue value = current; + for (final var prop : path.properties()) { + if (value instanceof JsonObject obj) { + value = obj.asMap().get(prop); + if (value == null) { + return null; + } + } else { + return null; + } + } + return value; + } + + private static Object jsonValueToComparable(JsonValue value) { + if (value == null) return null; + return switch (value) { + case JsonString s -> s.asString(); + case JsonNumber n -> n.asDouble(); + case JsonBoolean b -> b.asBoolean(); + case JsonNull ignored -> null; + default -> value; + }; + } + + @SuppressWarnings("unchecked") + private static boolean compareValues(Object left, JsonPathAst.ComparisonOp op, Object right) { + if (left == null || right == null) { + return switch (op) { + case EQ -> left == right; + case NE -> left != right; + default -> false; + }; + } + + // Try numeric comparison + switch (left) { + case Number leftNum when right instanceof Number rightNum -> { + final double l = leftNum.doubleValue(); + final double r = rightNum.doubleValue(); + return switch (op) { + case EQ -> l == r; + case NE -> l != r; + case LT -> l < r; + case LE -> l <= r; + case GT -> l > r; + case GE -> l >= r; + }; + } + + + // String comparison + case String ignored when right instanceof String -> { + @SuppressWarnings("rawtypes") final int cmp = ((Comparable) left).compareTo(right); + return switch (op) { + case EQ -> cmp == 0; + case NE -> cmp != 0; + case LT -> cmp < 0; + case LE -> cmp <= 0; + case GT -> cmp > 0; + case GE -> cmp >= 0; + }; + } + + + // Boolean comparison + case Boolean ignored when right instanceof Boolean -> { + return switch (op) { + case EQ -> left.equals(right); + case NE -> !left.equals(right); + default -> false; + }; + } + default -> { + } + } + + // Fallback equality + return switch (op) { + case EQ -> left.equals(right); + case NE -> !left.equals(right); + default -> false; + }; + } + + private static void evaluateUnion( + JsonPathAst.Union union, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + for (final var selector : union.selectors()) { + switch (selector) { + case JsonPathAst.ArrayIndex arr -> evaluateArrayIndex(arr, segments, index, current, root, results); + case JsonPathAst.PropertyAccess prop -> evaluatePropertyAccess(prop, segments, index, current, root, results); + default -> LOG.finer(() -> "Unsupported selector in union: " + selector); + } + } + } + + private static void evaluateScriptExpression( + JsonPathAst.ScriptExpression script, + List segments, + int index, + JsonValue current, + JsonValue root, + List results) { + + if (current instanceof JsonArray array) { + // Simple support for @.length-1 pattern + final var scriptText = script.script().trim(); + if (scriptText.equals("@.length-1")) { + final int lastIndex = array.asList().size() - 1; + if (lastIndex >= 0) { + evaluateSegments(segments, index + 1, array.asList().get(lastIndex), root, results); + } + } else { + LOG.warning(() -> "Unsupported script expression: " + scriptText); + } + } + } + + private static String reconstruct(JsonPathAst.Root root) { + final var sb = new StringBuilder("$"); + for (final var segment : root.segments()) { + appendSegment(sb, segment); + } + return sb.toString(); + } + + private static void appendSegment(StringBuilder sb, JsonPathAst.Segment segment) { + switch (segment) { + case JsonPathAst.PropertyAccess prop -> { + if (isSimpleIdentifier(prop.name())) { + sb.append(".").append(prop.name()); + } else { + sb.append("['").append(escape(prop.name())).append("']"); + } + } + case JsonPathAst.ArrayIndex arr -> sb.append("[").append(arr.index()).append("]"); + case JsonPathAst.ArraySlice slice -> { + sb.append("["); + if (slice.start() != null) sb.append(slice.start()); + sb.append(":"); + if (slice.end() != null) sb.append(slice.end()); + if (slice.step() != null) sb.append(":").append(slice.step()); + sb.append("]"); + } + case JsonPathAst.Wildcard ignored -> sb.append(".*"); + case JsonPathAst.RecursiveDescent desc -> { + sb.append(".."); + // RecursiveDescent target is usually PropertyAccess or Wildcard, + // but can be other things in theory. + // If target is PropertyAccess("foo"), append "foo". + // If target is Wildcard, append "*". + // Our AST structure wraps the target segment. + // We need to handle how it's appended. + // appendSegment prepends "." or "[" usually. + // But ".." replaces the dot. + // Let special case the target printing. + appendRecursiveTarget(sb, desc.target()); + } + case JsonPathAst.Filter filter -> { + sb.append("[?("); + appendFilterExpression(sb, filter.expression()); + sb.append(")]"); + } + case JsonPathAst.Union union -> { + sb.append("["); + final var selectors = union.selectors(); + for (int i = 0; i < selectors.size(); i++) { + if (i > 0) sb.append(","); + appendUnionSelector(sb, selectors.get(i)); + } + sb.append("]"); + } + case JsonPathAst.ScriptExpression script -> sb.append("[(").append(script.script()).append(")]"); + } + } + + private static void appendRecursiveTarget(StringBuilder sb, JsonPathAst.Segment target) { + if (target instanceof JsonPathAst.PropertyAccess(String name)) { + sb.append(name); // ..name + } else if (target instanceof JsonPathAst.Wildcard) { + sb.append("*"); // ..* + } else { + // Fallback for other types if they ever occur in recursive position + appendSegment(sb, target); + } + } + + private static void appendUnionSelector(StringBuilder sb, JsonPathAst.Segment selector) { + if (selector instanceof JsonPathAst.PropertyAccess(String name)) { + sb.append("'").append(escape(name)).append("'"); + } else if (selector instanceof JsonPathAst.ArrayIndex(int index)) { + sb.append(index); + } else { + // Fallback + appendSegment(sb, selector); + } + } + + private static void appendFilterExpression(StringBuilder sb, JsonPathAst.FilterExpression expr) { + switch (expr) { + case JsonPathAst.ExistsFilter exists -> appendFilterExpression(sb, exists.path()); // Should print the path + case JsonPathAst.ComparisonFilter comp -> { + appendFilterExpression(sb, comp.left()); + sb.append(comp.op().symbol()); + appendFilterExpression(sb, comp.right()); + } + case JsonPathAst.LogicalFilter logical -> { + if (logical.op() == JsonPathAst.LogicalOp.NOT) { + sb.append("!"); + appendFilterExpression(sb, logical.left()); + } else { + sb.append("("); + appendFilterExpression(sb, logical.left()); + sb.append(" ").append(logical.op().symbol()).append(" "); + appendFilterExpression(sb, logical.right()); + sb.append(")"); + } + } + case JsonPathAst.CurrentNode ignored -> sb.append("@"); + case JsonPathAst.PropertyPath path -> { + sb.append("@"); + for (String p : path.properties()) { + if (isSimpleIdentifier(p)) { + sb.append(".").append(p); + } else { + sb.append("['").append(escape(p)).append("']"); + } + } + } + case JsonPathAst.LiteralValue lit -> { + if (lit.value() instanceof String s) { + sb.append("'").append(escape(s)).append("'"); + } else { + sb.append(lit.value()); + } + } + } + } + + private static boolean isSimpleIdentifier(String name) { + if (name.isEmpty()) return false; + if (!Character.isJavaIdentifierStart(name.charAt(0))) return false; + for (int i = 1; i < name.length(); i++) { + if (!Character.isJavaIdentifierPart(name.charAt(i))) return false; + } + return true; + } + + private static String escape(String s) { + return s.replace("'", "\\'"); + } +} From 826f4370ced5d10ace62561a813c632952bdd428 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:24:23 +0000 Subject: [PATCH 3/7] Issue #178: extract filter evaluation helpers shared by both engines JsonPathHelpers now owns resolvePropertyPath, toJsonComparable, and compareValues exactly as the interpreter evaluated them; the interpreted engine delegates to them and the bytecode-generated engine (next commit) calls the same methods, giving compiled/interpreted parity for filter semantics by construction. All 100 existing JsonPath tests pass. To verify: mvn -pl json-java21-jsonpath test -Djava.util.logging.ConsoleHandler.level=INFO (100 tests green). --- .../json/java21/jsonpath/JsonPathHelpers.java | 139 ++++++++++++++++++ .../java21/jsonpath/JsonPathInterpreted.java | 98 +----------- 2 files changed, 145 insertions(+), 92 deletions(-) create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java new file mode 100644 index 00000000..0d44fa89 --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java @@ -0,0 +1,139 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.JsonArray; +import jdk.incubator.java.util.json.JsonBoolean; +import jdk.incubator.java.util.json.JsonNull; +import jdk.incubator.java.util.json.JsonNumber; +import jdk.incubator.java.util.json.JsonObject; +import jdk.incubator.java.util.json.JsonString; +import jdk.incubator.java.util.json.JsonValue; + +import java.util.List; +import java.util.logging.Logger; + +/// Evaluation helpers shared verbatim by both JsonPath engines. +/// +/// The interpreted engine and the bytecode-generated engine (JDK 24+ `JsonPathCodegen`) +/// both call these for filter-expression evaluation, so comparisons, path resolution, +/// and diagnostics behave identically regardless of which engine runs a query. +final class JsonPathHelpers { + + private static final Logger LOG = Logger.getLogger(JsonPathHelpers.class.getName()); + + private JsonPathHelpers() {} + + /// Resolves a property path against a JsonValue. + /// @param current the JSON value to resolve from + /// @param properties the property names, in order + /// @return the resolved value, or null when any step is missing or the value is not an object + static JsonValue resolvePropertyPath(JsonValue current, List properties) { + JsonValue value = current; + for (final var prop : properties) { + if (value instanceof JsonObject obj) { + value = obj.asMap().get(prop); + if (value == null) { + return null; + } + } else { + return null; + } + } + return value; + } + + /// Converts a JsonValue to a comparable object for filter comparisons. + /// @param value the JSON value to convert + /// @return a String, Double, or Boolean; null for JSON null and other value kinds + static Object toJsonComparable(JsonValue value) { + if (value == null) return null; + return switch (value) { + case JsonString s -> s.asString(); + case JsonNumber n -> n.asDouble(); + case JsonBoolean b -> b.asBoolean(); + case JsonNull ignored -> null; + default -> value; + }; + } + + /// Evaluates a filter comparison using the JsonPath engine's comparison rules. + /// @param left the left operand (possibly null) + /// @param op the comparison operator + /// @param right the right operand (possibly null) + /// @return true when the comparison is satisfied + @SuppressWarnings("unchecked") + static boolean compareValues(Object left, JsonPathAst.ComparisonOp op, Object right) { + if (left == null || right == null) { + return switch (op) { + case EQ -> left == right; + case NE -> left != right; + default -> false; + }; + } + + // Try numeric comparison + switch (left) { + case Number leftNum when right instanceof Number rightNum -> { + final double l = leftNum.doubleValue(); + final double r = rightNum.doubleValue(); + return switch (op) { + case EQ -> l == r; + case NE -> l != r; + case LT -> l < r; + case LE -> l <= r; + case GT -> l > r; + case GE -> l >= r; + }; + } + + // String comparison + case String ignored when right instanceof String -> { + @SuppressWarnings("rawtypes") final int cmp = ((Comparable) left).compareTo(right); + return switch (op) { + case EQ -> cmp == 0; + case NE -> cmp != 0; + case LT -> cmp < 0; + case LE -> cmp <= 0; + case GT -> cmp > 0; + case GE -> cmp >= 0; + }; + } + + // Boolean comparison + case Boolean ignored when right instanceof Boolean -> { + return switch (op) { + case EQ -> left.equals(right); + case NE -> !left.equals(right); + default -> false; + }; + } + default -> { + } + } + + // Fallback equality + return switch (op) { + case EQ -> left.equals(right); + case NE -> !left.equals(right); + default -> false; + }; + } + + /// Logs an unsupported script expression in the same way the interpreter does. + /// Generated executors call this so compiled queries surface the same diagnostics. + /// @param script the unsupported script text + static void unsupportedScript(String script) { + LOG.warning(() -> "Unsupported script expression: " + script); + } + + /// Logs an unsupported recursive-descent target in the same way the interpreter does. + /// @param target the unsupported target segment + static void unsupportedRecursiveTarget(JsonPathAst.Segment target) { + LOG.finer(() -> "Unsupported target in recursive descent: " + target); + } + + /// Logs an unsupported union selector in the same way the interpreter does. + /// @param selector the unsupported selector segment + static void unsupportedUnionSelector(JsonPathAst.Segment selector) { + LOG.finer(() -> "Unsupported selector in union: " + selector); + } +} diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java index 265dcccb..9ee64cd9 100644 --- a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java @@ -275,13 +275,13 @@ private static void evaluateFilter( private static boolean matchesFilter(JsonPathAst.FilterExpression expr, JsonValue current) { return switch (expr) { case JsonPathAst.ExistsFilter exists -> { - final var value = resolvePropertyPath(exists.path(), current); + final var value = JsonPathHelpers.resolvePropertyPath(current, exists.path().properties()); yield value != null; } case JsonPathAst.ComparisonFilter comp -> { final var leftValue = resolveFilterExpression(comp.left(), current); final var rightValue = resolveFilterExpression(comp.right(), current); - yield compareValues(leftValue, comp.op(), rightValue); + yield JsonPathHelpers.compareValues(leftValue, comp.op(), rightValue); } case JsonPathAst.LogicalFilter logical -> { final var leftMatch = matchesFilter(logical.left(), current); @@ -292,7 +292,7 @@ yield switch (logical.op()) { }; } case JsonPathAst.CurrentNode ignored1 -> true; - case JsonPathAst.PropertyPath path -> resolvePropertyPath(path, current) != null; + case JsonPathAst.PropertyPath path -> JsonPathHelpers.resolvePropertyPath(current, path.properties()) != null; case JsonPathAst.LiteralValue ignored -> true; }; } @@ -300,101 +300,15 @@ yield switch (logical.op()) { private static Object resolveFilterExpression(JsonPathAst.FilterExpression expr, JsonValue current) { return switch (expr) { case JsonPathAst.PropertyPath path -> { - final var value = resolvePropertyPath(path, current); - yield jsonValueToComparable(value); + final var value = JsonPathHelpers.resolvePropertyPath(current, path.properties()); + yield JsonPathHelpers.toJsonComparable(value); } case JsonPathAst.LiteralValue lit -> lit.value(); - case JsonPathAst.CurrentNode ignored -> jsonValueToComparable(current); + case JsonPathAst.CurrentNode ignored -> JsonPathHelpers.toJsonComparable(current); default -> null; }; } - private static JsonValue resolvePropertyPath(JsonPathAst.PropertyPath path, JsonValue current) { - JsonValue value = current; - for (final var prop : path.properties()) { - if (value instanceof JsonObject obj) { - value = obj.asMap().get(prop); - if (value == null) { - return null; - } - } else { - return null; - } - } - return value; - } - - private static Object jsonValueToComparable(JsonValue value) { - if (value == null) return null; - return switch (value) { - case JsonString s -> s.asString(); - case JsonNumber n -> n.asDouble(); - case JsonBoolean b -> b.asBoolean(); - case JsonNull ignored -> null; - default -> value; - }; - } - - @SuppressWarnings("unchecked") - private static boolean compareValues(Object left, JsonPathAst.ComparisonOp op, Object right) { - if (left == null || right == null) { - return switch (op) { - case EQ -> left == right; - case NE -> left != right; - default -> false; - }; - } - - // Try numeric comparison - switch (left) { - case Number leftNum when right instanceof Number rightNum -> { - final double l = leftNum.doubleValue(); - final double r = rightNum.doubleValue(); - return switch (op) { - case EQ -> l == r; - case NE -> l != r; - case LT -> l < r; - case LE -> l <= r; - case GT -> l > r; - case GE -> l >= r; - }; - } - - - // String comparison - case String ignored when right instanceof String -> { - @SuppressWarnings("rawtypes") final int cmp = ((Comparable) left).compareTo(right); - return switch (op) { - case EQ -> cmp == 0; - case NE -> cmp != 0; - case LT -> cmp < 0; - case LE -> cmp <= 0; - case GT -> cmp > 0; - case GE -> cmp >= 0; - }; - } - - - // Boolean comparison - case Boolean ignored when right instanceof Boolean -> { - return switch (op) { - case EQ -> left.equals(right); - case NE -> !left.equals(right); - default -> false; - }; - } - default -> { - } - } - - // Fallback equality - return switch (op) { - case EQ -> left.equals(right); - case NE -> !left.equals(right); - default -> false; - }; - } - private static void evaluateUnion( JsonPathAst.Union union, List segments, From 1dd293897c8df5bbc963a3df0d13556a5af2eafa Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:59:54 +0000 Subject: [PATCH 4/7] Issue #178: share normalizeIndex through JsonPathHelpers Moves the slice index normalization into the helpers shared by both engines so the interpreted and compiled engines normalize slice bounds identically; the interpreter now delegates. All 100 existing JsonPath tests pass on both JDK 21 and JDK 25. To verify: mvn -pl json-java21-jsonpath test -Djava.util.logging.ConsoleHandler.level=INFO (100 tests green). --- .../json/java21/jsonpath/JsonPathHelpers.java | 8 ++++++++ .../json/java21/jsonpath/JsonPathInterpreted.java | 15 ++++----------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java index 0d44fa89..085cbc00 100644 --- a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathHelpers.java @@ -118,6 +118,14 @@ static boolean compareValues(Object left, JsonPathAst.ComparisonOp op, Object ri }; } + /// Normalizes an array index against an array size. + /// @param index the index, possibly counting from the end + /// @param size the array size + /// @return the resolved non-negative index (may be out of bounds) + static int normalizeIndex(int index, int size) { + return index < 0 ? size + index : index; + } + /// Logs an unsupported script expression in the same way the interpreter does. /// Generated executors call this so compiled queries surface the same diagnostics. /// @param script the unsupported script text diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java index 9ee64cd9..36b9f9a8 100644 --- a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathInterpreted.java @@ -142,8 +142,8 @@ private static void evaluateArraySlice( } if (step > 0) { - int start = slice.start() != null ? normalizeIndex(slice.start(), size) : 0; - int end = slice.end() != null ? normalizeIndex(slice.end(), size) : size; + int start = slice.start() != null ? JsonPathHelpers.normalizeIndex(slice.start(), size) : 0; + int end = slice.end() != null ? JsonPathHelpers.normalizeIndex(slice.end(), size) : size; start = Math.max(0, Math.min(start, size)); end = Math.max(0, Math.min(end, size)); @@ -152,8 +152,8 @@ private static void evaluateArraySlice( evaluateSegments(segments, index + 1, elements.get(i), root, results); } } else { - int start = slice.start() != null ? normalizeIndex(slice.start(), size) : size - 1; - final int end = slice.end() != null ? normalizeIndex(slice.end(), size) : -1; + int start = slice.start() != null ? JsonPathHelpers.normalizeIndex(slice.start(), size) : size - 1; + final int end = slice.end() != null ? JsonPathHelpers.normalizeIndex(slice.end(), size) : -1; start = Math.max(0, Math.min(start, size - 1)); @@ -164,13 +164,6 @@ private static void evaluateArraySlice( } } - private static int normalizeIndex(int index, int size) { - if (index < 0) { - return size + index; - } - return index; - } - private static void evaluateWildcard( List segments, int index, From fac937576744022f7e2a97f225bf5fc1469bab56 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:59:59 +0000 Subject: [PATCH 5/7] Issue #178: add bytecode-generated JsonPath engine with parity tests Compiled engine in the jtd-codegen style: JsonPathCodegen.compiles any parsed JsonPath with the JDK 24 ClassFile API (JEP 484) into a Java 21 classfile (ClassFile.JAVA_21_VERSION, v65) implementing the package-private JsonPathExecutor; compileBytes exposes raw bytes for ahead-of-time, jtd2jar-style tooling. The emitter produces one continuation method per segment, mirroring the interpreted engine's evaluation order exactly; filter predicates call the shared JsonPathHelpers so both engines agree by construction. TDD: JsonPathCompilerParityTest (red against the emitter stub, then green) reuses the existing test corpus (64 expression/document cases plus 6 codegen-mechanics tests). The Maven profile jsonpath-codegen activates on JDK 24+ and compiles the generator and parity tests at release 24; on JDK 21 the interpreted engine builds unchanged and all 100 existing tests pass. Docs updated with the two-engine contract. To verify: mvn -pl json-java21-jsonpath test -Djava.util.logging.ConsoleHandler.level=INFO (170 tests green on JDK 25; 100 on JDK 21). --- json-java21-jsonpath/AGENTS.md | 11 +- json-java21-jsonpath/README.md | 17 +- json-java21-jsonpath/pom.xml | 97 +++ .../jsonpath/JsonPathBytecodeEmitter.java | 801 ++++++++++++++++++ .../json/java21/jsonpath/JsonPathCodegen.java | 78 ++ .../java21/jsonpath/JsonPathCodegenTest.java | 80 ++ .../jsonpath/JsonPathCompilerParityTest.java | 180 ++++ 7 files changed, 1252 insertions(+), 12 deletions(-) create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java create mode 100644 json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCodegen.java create mode 100644 json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCodegenTest.java create mode 100644 json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCompilerParityTest.java diff --git a/json-java21-jsonpath/AGENTS.md b/json-java21-jsonpath/AGENTS.md index 2990fa5b..0e364a39 100644 --- a/json-java21-jsonpath/AGENTS.md +++ b/json-java21-jsonpath/AGENTS.md @@ -15,12 +15,13 @@ Stable code entry points: - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathParseException.java` - `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathStreams.java` -Compiled engine (JDK 24+ only; the Maven profile `jsonpath-codegen` activates on JDK 24+ and adds `src/main/codegen/java` plus `src/test/codegen/java`): -- `json-java21-jsonpath/src/main/codegen/java/json/java21/jsonpath/JsonPathCodegen.java` (ClassFile API, JEP 484; emits `ClassFile.JAVA_21_VERSION` / version 65 bytecode) -- `json-java21-jsonpath/src/main/codegen/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java` (AST-to-bytecode emitter) -- `json-java21-jsonpath/src/test/codegen/java/json/java21/jsonpath/JsonPathCompilerParityTest.java` (interpreted == generated parity over the existing test corpus) +Compiled engine (JDK 24+ only): on JDK 21, the Maven profile `jsonpath-codegen` does not activate and `JsonPathCodegen`/`JsonPathBytecodeEmitter` plus the parity tests are excluded from compilation; on JDK 24+ they are compiled at release 24 (mirroring the jtd-codegen parent profile): +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCodegen.java` (entry point; ClassFile API, JEP 484; emits `ClassFile.JAVA_21_VERSION` / version 65 bytecode) +- `json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java` (AST-to-bytecode emitter) +- `json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCompilerParityTest.java` (interpreted == generated parity over the existing test corpus) +- `json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCodegenTest.java` (codegen mechanics: facade, idempotence, classfile version) When changing syntax/behavior: - Update `JsonPathAst` + `JsonPathParser` + `JsonPath` together. -- Mirror the change in `JsonPathBytecodeEmitter` (and `JsonPathHelpers` when shared evaluation logic moves); the parity test suite guards the interpreted/generated contract. +- Mirror the change in `JsonPathBytecodeEmitter` (call sites of shared `JsonPathHelpers` evaluation) (and `JsonPathHelpers` when shared evaluation logic moves); the parity test suite guards the interpreted/generated contract. - Add parser + evaluation tests; new tests should extend `JsonPathLoggingConfig`; add a matching parity entry for any new operator. diff --git a/json-java21-jsonpath/README.md b/json-java21-jsonpath/README.md index 99803c23..7548def2 100644 --- a/json-java21-jsonpath/README.md +++ b/json-java21-jsonpath/README.md @@ -67,29 +67,32 @@ This module ships the same JsonPath language with two interchangeable engines be | Engine | Class | Availability | Mechanism | |---|---|---|---| | Interpreted | `JsonPath.parse(...)` result | JDK 21+ (default) | walks the `JsonPathAst` tree per query | -| Compiled | `JsonPath.compile(...)` result | JDK 24+ runtime | bytecode generated with the JDK 24 ClassFile API (JEP 484), targeting Java 21 bytecode (`ClassFile.JAVA_21_VERSION`, class file version 65) | +| Compiled | `JsonPathCodegen.compile(...)` result | JDK 24+ runtime | bytecode generated with the JDK 24 ClassFile API (JEP 484), targeting Java 21 bytecode (`ClassFile.JAVA_21_VERSION`, class file version 65) | Both engines implement the same `JsonPath` public surface, so callers can hand either one to the same API. The compiled engine mirrors the approach already shipped for JTD validation in [`json-java21-jtd-codegen`](../json-java21-jtd-codegen/README.md) (`JtdCodegen` / `JtdValidator.compileGenerated`). ### Using the Compiled Engine ```java -// Parse once, compile for the best repeated-query performance -JsonPath path = JsonPath.parse("$.store.book[*].author"); +// Parse once, compile for the best repeated-query performance (JDK 24+) +JsonPath path = JsonPathCodegen.compile(JsonPath.parse("$.store.book[*].author")); for (JsonValue doc : documents) { - List results = JsonPath.compile(path).query(doc); + List results = path.query(doc); // process results... } ``` -Compiling an already-compiled path returns the same instance (compilation is idempotent). The compiled engine keeps the original path text (`toString()`) and the AST (`ast()`), so a compiled path is a drop-in replacement anywhere an interpreted path is accepted. +`JsonPathCodegen.compile(...)` mirrors `JtdValidator.compileGenerated(...)`: it accepts any `JsonPath`, returns a `JsonPath` implementing the same public surface, and is idempotent (compiling a compiled path returns it unchanged). + +The compiled engine keeps the original path text (`toString()`) and the AST (`ast()`), so a compiled path is a drop-in replacement anywhere an interpreted path is accepted. ### Runtime Requirements - **Interpreted engine**: JDK 21+; no dependency on the ClassFile API; unchanged semantics. -- **Compiled engine**: generating classes requires a JDK 24+ runtime (`java.lang.classfile`, JEP 484). Calling `compile()` on JDK 21 or earlier fails with a `NoClassDefFoundError`; use the interpreted engine there. The generated classes are Java 21 bytecode and only need Java 21 API surface at query time. -- **Ahead-of-time (build-time) tooling**: `JsonPathCodegen.compileBytes(...)` returns the raw generated classfile bytes without loading them, in the same style as `JtdCodegen.compileBytes(...)` for `jtd2jar`-style standalone JAR builds. +- **Compiled engine**: generating classes requires a JDK 24+ runtime (`java.lang.classfile`, JEP 484) because the generator is compiled into the artifact only on JDK 24+. The generated classes are Java 21 bytecode and only need Java 21 API surface at query time. +- **Ahead-of-time (build-time) tooling**: `JsonPathCodegen.compileBytes(...)` returns the raw generated classfile bytes without loading them, in the same style as `JtdCodegen.compileBytes(...)` for `jtd2jar`-style standalone JAR builds. Generated executor classes are always emitted into the `json.java21.jsonpath` package so they can implement the package-private executor interface. +- **Diagnostics**: semantics and result order are identical between the engines. One deliberate, exact difference: when an expression carries an unsupported recursive-descent target or union selector, the interpreted engine logs it at `FINER` for every visited node, while the compiled engine logs it once at compile time; unsupported script expressions log `WARNING` at query time in both engines. ### Parity Guarantee diff --git a/json-java21-jsonpath/pom.xml b/json-java21-jsonpath/pom.xml index 575e28c1..3b96b9ba 100644 --- a/json-java21-jsonpath/pom.xml +++ b/json-java21-jsonpath/pom.xml @@ -72,6 +72,29 @@ -Xdiags:verbose + + + + default-compile + + + json/java21/jsonpath/JsonPathCodegen.java + json/java21/jsonpath/JsonPathBytecodeEmitter.java + + + + + default-testCompile + + + json/java21/jsonpath/JsonPathCodegenTest.java + json/java21/jsonpath/JsonPathCompilerParityTest.java + + + + org.apache.maven.plugins @@ -80,6 +103,80 @@ -ea + + org.apache.maven.plugins + maven-javadoc-plugin + + + + json/java21/jsonpath/JsonPathCodegen.java + json/java21/jsonpath/JsonPathBytecodeEmitter.java + + + + + + + + jsonpath-codegen + + [24,) + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + compile-codegen + + compile + + + 24 + + json/java21/jsonpath/JsonPathCodegen.java + json/java21/jsonpath/JsonPathBytecodeEmitter.java + + + + + compile-codegen-tests + + testCompile + + + 24 + + json/java21/jsonpath/JsonPathCodegenTest.java + json/java21/jsonpath/JsonPathCompilerParityTest.java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + json/java21/jsonpath/JsonPathCodegen.java + json/java21/jsonpath/JsonPathBytecodeEmitter.java + + + + + + + diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java new file mode 100644 index 00000000..c8a9ebed --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathBytecodeEmitter.java @@ -0,0 +1,801 @@ +package json.java21.jsonpath; + +import java.lang.classfile.ClassBuilder; +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.Label; +import java.lang.classfile.TypeKind; +import java.lang.classfile.attribute.SourceFileAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.MethodTypeDesc; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +/// Emits a JsonPath executor class from a parsed [JsonPathAst] tree. +/// +/// The generated class implements the package-private [JsonPathExecutor] +/// interface as Java 21 bytecode (`ClassFile.JAVA_21_VERSION`, version 65), +/// with one private static continuation method per path segment, mirroring the +/// interpreted engine's evaluation order exactly. Filter predicates and +/// comparisons delegate to the [JsonPathHelpers] methods, the single source of +/// truth shared with the interpreted engine. +/// +/// This class requires JDK 24+ (ClassFile API, JEP 484) and lives in the +/// profile-gated codegen source root; see the module README ("Two Engines"). +final class JsonPathBytecodeEmitter { + + private static final Logger LOG = Logger.getLogger(JsonPathBytecodeEmitter.class.getName()); + + /// The one runtime package generated executors may be emitted into: generated + /// classes implement the package-private [JsonPathExecutor] interface, so they + /// must be defined in a package that can access it. + static final String SUPPORTED_PACKAGE = "json.java21.jsonpath"; + + // -- class descriptors -- + private static final ClassDesc CD_List = ClassDesc.of("java.util.List"); + private static final ClassDesc CD_Map = ClassDesc.of("java.util.Map"); + private static final ClassDesc CD_Collection = ClassDesc.of("java.util.Collection"); + private static final ClassDesc CD_Iterator = ClassDesc.of("java.util.Iterator"); + private static final ClassDesc CD_ArrayList = ClassDesc.of("java.util.ArrayList"); + private static final ClassDesc CD_Arrays = ClassDesc.of("java.util.Arrays"); + private static final ClassDesc CD_Math = ClassDesc.of("java.lang.Math"); + private static final ClassDesc CD_JsonValue = ClassDesc.of("jdk.incubator.java.util.json.JsonValue"); + private static final ClassDesc CD_JsonObject = ClassDesc.of("jdk.incubator.java.util.json.JsonObject"); + private static final ClassDesc CD_JsonArray = ClassDesc.of("jdk.incubator.java.util.json.JsonArray"); + private static final ClassDesc CD_ComparisonOp = ClassDesc.of("json.java21.jsonpath.JsonPathAst$ComparisonOp"); + private static final ClassDesc CD_JsonPathExecutor = ClassDesc.of("json.java21.jsonpath.JsonPathExecutor"); + private static final ClassDesc CD_Helpers = ClassDesc.of("json.java21.jsonpath.JsonPathHelpers"); + + // -- method type descriptors -- + private static final MethodTypeDesc MTD_EXECUTE = MethodTypeDesc.of(CD_List, CD_JsonValue, CD_JsonValue); + private static final MethodTypeDesc MTD_CONT = MethodTypeDesc.of(ConstantDescs.CD_void, CD_JsonValue, CD_JsonValue, CD_List); + private static final MethodTypeDesc MTD_PRED = MethodTypeDesc.of(ConstantDescs.CD_boolean, CD_JsonValue); + private static final MethodTypeDesc MTD_MAP = MethodTypeDesc.of(CD_Map); + private static final MethodTypeDesc MTD_LIST = MethodTypeDesc.of(CD_List); + private static final MethodTypeDesc MTD_COLLECTION = MethodTypeDesc.of(CD_Collection); + private static final MethodTypeDesc MTD_ITERATOR = MethodTypeDesc.of(CD_Iterator); + private static final MethodTypeDesc MTD_GET_OBJECT = MethodTypeDesc.of(ConstantDescs.CD_Object, ConstantDescs.CD_Object); + private static final MethodTypeDesc MTD_OBJECT_INT = MethodTypeDesc.of(ConstantDescs.CD_Object, ConstantDescs.CD_int); + private static final MethodTypeDesc MTD_INT = MethodTypeDesc.of(ConstantDescs.CD_int); + private static final MethodTypeDesc MTD_ADD = MethodTypeDesc.of(ConstantDescs.CD_boolean, ConstantDescs.CD_Object); + private static final MethodTypeDesc MTD_ITERATOR_HAS_NEXT = MethodTypeDesc.of(ConstantDescs.CD_boolean); + private static final MethodTypeDesc MTD_ITERATOR_NEXT = MethodTypeDesc.of(ConstantDescs.CD_Object); + private static final MethodTypeDesc MTD_II_I = MethodTypeDesc.of(ConstantDescs.CD_int, ConstantDescs.CD_int, ConstantDescs.CD_int); + private static final MethodTypeDesc MTD_INTEGER_VALUE_OF = MethodTypeDesc.of(ConstantDescs.CD_Integer, ConstantDescs.CD_int); + private static final MethodTypeDesc MTD_LONG_VALUE_OF = MethodTypeDesc.of(ConstantDescs.CD_Long, ConstantDescs.CD_long); + private static final MethodTypeDesc MTD_DOUBLE_VALUE_OF = MethodTypeDesc.of(ConstantDescs.CD_Double, ConstantDescs.CD_double); + private static final MethodTypeDesc MTD_FLOAT_VALUE_OF = MethodTypeDesc.of(ConstantDescs.CD_Float, ConstantDescs.CD_float); + private static final MethodTypeDesc MTD_RESOLVE_PATH = MethodTypeDesc.of(CD_JsonValue, CD_JsonValue, CD_List); + private static final MethodTypeDesc MTD_TO_COMPARABLE = MethodTypeDesc.of(ConstantDescs.CD_Object, CD_JsonValue); + private static final MethodTypeDesc MTD_COMPARE = MethodTypeDesc.of(ConstantDescs.CD_boolean, ConstantDescs.CD_Object, CD_ComparisonOp, ConstantDescs.CD_Object); + private static final MethodTypeDesc MTD_VOID_STRING = MethodTypeDesc.of(ConstantDescs.CD_void, ConstantDescs.CD_String); + private static final MethodTypeDesc MTD_ARRAYS_AS_LIST = MethodTypeDesc.of(CD_List, ConstantDescs.CD_Object.arrayType()); + + private final ClassBuilder clb; + private final ClassDesc self; + private final List segments; + private final Map predicateMethods = new HashMap<>(); + private final Map, Integer> pathConstants = new HashMap<>(); + + private JsonPathBytecodeEmitter(ClassBuilder clb, ClassDesc self, List segments) { + this.clb = clb; + this.self = self; + this.segments = segments; + } + + /// Emits the classfile bytes for a compiled JsonPath executor. + /// + /// @param packageName target package (must be the supported runtime package so the + /// generated class can implement the package-private executor) + /// @param className simple class name within the target package + /// @param ast the parsed JsonPath AST to compile + /// @return the generated classfile bytes + static byte[] emit(String packageName, String className, JsonPathAst.Root ast) { + if (!SUPPORTED_PACKAGE.equals(packageName)) { + throw new IllegalArgumentException( + "generated executors can only be emitted into package '" + SUPPORTED_PACKAGE + + "' so they implement the package-private JsonPathExecutor interface, got: '" + + packageName + "'"); + } + final var internalName = packageName.replace('.', '/') + "/" + className; + final var classDesc = ClassDesc.ofInternalName(internalName); + LOG.fine(() -> "Emitting JsonPath executor " + internalName + " with " + ast.segments().size() + " segments"); + + return ClassFile.of().build(classDesc, clb -> { + clb.withVersion(ClassFile.JAVA_21_VERSION, 0); + clb.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_FINAL); + clb.withSuperclass(ConstantDescs.CD_Object); + clb.withInterfaceSymbols(CD_JsonPathExecutor); + clb.with(SourceFileAttribute.of("JsonPathCodegen")); + new JsonPathBytecodeEmitter(clb, classDesc, ast.segments()).emitClass(); + }); + } + + private void emitClass() { + emitConstructor(); + emitExecute(); + for (final var segment : segments) { + if (segment instanceof JsonPathAst.Filter(JsonPathAst.FilterExpression expression)) { + predicateMethodFor(expression); + } + } + emitContinuation(0); + emitPathConstantFields(); + } + + private void emitConstructor() { + clb.withMethodBody(ConstantDescs.INIT_NAME, ConstantDescs.MTD_void, ClassFile.ACC_PUBLIC, cob -> { + cob.aload(0); + cob.invokespecial(ConstantDescs.CD_Object, ConstantDescs.INIT_NAME, ConstantDescs.MTD_void); + cob.return_(); + }); + } + + /// Instance method slots: 0 = this, 1 = current, 2 = root; the fresh + /// results list is allocated into the next local slot. + private void emitExecute() { + clb.withMethodBody("execute", MTD_EXECUTE, ClassFile.ACC_PUBLIC, cob -> { + cob.new_(CD_ArrayList); + cob.dup(); + cob.invokespecial(CD_ArrayList, ConstantDescs.INIT_NAME, ConstantDescs.MTD_void); + final int resultsSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(resultsSlot); + cob.aload(1); + cob.aload(2); + cob.aload(resultsSlot); + cob.invokestatic(self, "cont0", MTD_CONT); + cob.aload(resultsSlot); + cob.areturn(); + }); + } + + /// Emits `contK`, the static continuation method for segment K. Conventions + /// for continuation methods: slot 0 = current value, slot 1 = root, slot 2 = results. + private void emitContinuation(int k) { + clb.withMethodBody("cont" + k, MTD_CONT, ClassFile.ACC_PRIVATE | ClassFile.ACC_STATIC, cob -> { + if (k >= segments.size()) { + emitTerminal(cob); + return; + } + emitSegment(k, cob); + }); + if (k < segments.size()) { + emitContinuation(k + 1); + } + } + + /// Terminal continuation: the whole path matched, so record the current node. + private static void emitTerminal(CodeBuilder cob) { + cob.aload(2); + cob.aload(0); + cob.invokeinterface(CD_List, "add", MTD_ADD); + cob.pop(); + cob.return_(); + } + + /// Invokes the continuation for the next segment with the given candidate value. + /// Needs the emitter's `self` descriptor, so it stays an instance method. + private void emitContinueWith(CodeBuilder cob, int k, int valueSlot) { + cob.aload(valueSlot); + cob.aload(1); + cob.aload(2); + cob.invokestatic(self, "cont" + (k + 1), MTD_CONT); + } + + // -- segment emission -- + + private void emitSegment(int k, CodeBuilder cob) { + final var done = cob.newLabel(); + switch (segments.get(k)) { + case JsonPathAst.PropertyAccess(String name) -> + emitPropertyMatch(cob, k, name, done); + case JsonPathAst.ArrayIndex(int index) -> + emitIndexMatch(cob, k, index, done); + case JsonPathAst.ArraySlice(Integer start, Integer end, Integer step) -> + emitSlice(cob, k, start, end, step, done); + case JsonPathAst.Wildcard ignored -> + emitChildren(cob, k, done); + case JsonPathAst.RecursiveDescent(JsonPathAst.Segment target) -> { + // descK applies the target at the current level and then walks + // every descendant, mirroring evaluateRecursiveDescent. + emitRecursiveDescent(k, target); + cob.aload(0); + cob.aload(1); + cob.aload(2); + cob.invokestatic(self, "desc" + k, MTD_CONT); + } + case JsonPathAst.Filter(JsonPathAst.FilterExpression expression) -> { + final int predMethod = predicateMethods.get(expression); + cob.aload(0); + cob.instanceOf(CD_JsonArray); + cob.ifeq(done); + final int listSlot = emitAsList(cob); + emitFilterLoop(cob, k, listSlot, predMethod); + } + case JsonPathAst.Union(List selectors) -> { + for (final var selector : selectors) { + // each selector jumps to its own end label on failure so the + // remaining selectors still evaluate + final var selectorDone = cob.newLabel(); + switch (selector) { + case JsonPathAst.PropertyAccess(String name) -> + emitPropertyMatch(cob, k, name, selectorDone); + case JsonPathAst.ArrayIndex(int index) -> + emitIndexMatch(cob, k, index, selectorDone); + default -> { + LOG.finer(() -> "Unsupported selector in union: " + selector); + cob.labelBinding(selectorDone); + continue; + } + } + cob.labelBinding(selectorDone); + } + } + case JsonPathAst.ScriptExpression(String script) -> + emitScriptExpression(cob, k, script, done); + } + cob.labelBinding(done); + cob.return_(); + } + + /// Matches a named property: current must be a JsonObject holding the key. + private void emitPropertyMatch(CodeBuilder cob, int k, String name, Label done) { + cob.aload(0); + cob.instanceOf(CD_JsonObject); + cob.ifeq(done); + cob.aload(0); + cob.checkcast(CD_JsonObject); + cob.invokeinterface(CD_JsonObject, "asMap", MTD_MAP); + cob.ldc(name); + cob.invokeinterface(CD_Map, "get", MTD_GET_OBJECT); + cob.checkcast(CD_JsonValue); + final int valueSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(valueSlot); + cob.aload(valueSlot); + cob.instanceOf(CD_JsonValue); // false for null: mirrors the interpreter's null check + cob.ifeq(done); + emitContinueWith(cob, k, valueSlot); + } + + /// Matches an array element by absolute or negative-from-end index. + private void emitIndexMatch(CodeBuilder cob, int k, int index, Label done) { + cob.aload(0); + cob.instanceOf(CD_JsonArray); + cob.ifeq(done); + final int listSlot = emitAsList(cob); + final int sizeSlot = emitListSize(cob, listSlot); + final int idxSlot = cob.allocateLocal(TypeKind.INT); + // idx = index < 0 ? size + index : index + final var negativeLabel = cob.newLabel(); + final var storeLabel = cob.newLabel(); + cob.ldc(index); + cob.iflt(negativeLabel); + cob.ldc(index); + cob.goto_(storeLabel); + cob.labelBinding(negativeLabel); + cob.iload(sizeSlot); + cob.ldc(index); + cob.iadd(); + cob.labelBinding(storeLabel); + cob.istore(idxSlot); + cob.iload(idxSlot); + cob.iflt(done); + cob.iload(idxSlot); + cob.iload(sizeSlot); + cob.if_icmpge(done); + cob.aload(listSlot); + cob.iload(idxSlot); + cob.invokeinterface(CD_List, "get", MTD_OBJECT_INT); + cob.checkcast(CD_JsonValue); + final int elementSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(elementSlot); + emitContinueWith(cob, k, elementSlot); + } + + /// Matches all direct children (object values then array elements). + private void emitChildren(CodeBuilder cob, int k, Label done) { + emitWalkChildren(cob, "cont" + (k + 1), done); + } + + /// Walks all direct children (object values then array elements) and invokes + /// the named static continuation method with (child, root, results) for each. + /// Used both by the wildcard segment (continuing with the next segment) and + /// by recursive descent (re-entering the descent itself). + private void emitWalkChildren(CodeBuilder cob, String callTarget, Label done) { + final var arrayLabel = cob.newLabel(); + final var objectDone = cob.newLabel(); + + // Object values + cob.aload(0); + cob.instanceOf(CD_JsonObject); + cob.ifeq(arrayLabel); + final var loopStart = cob.newLabel(); + final var loopEnd = cob.newLabel(); + cob.aload(0); + cob.checkcast(CD_JsonObject); + cob.invokeinterface(CD_JsonObject, "asMap", MTD_MAP); + cob.invokeinterface(CD_Map, "values", MTD_COLLECTION); + cob.invokeinterface(CD_Collection, "iterator", MTD_ITERATOR); + final int iteratorSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(iteratorSlot); + cob.labelBinding(loopStart); + cob.aload(iteratorSlot); + cob.invokeinterface(CD_Iterator, "hasNext", MTD_ITERATOR_HAS_NEXT); + cob.ifeq(loopEnd); + cob.aload(iteratorSlot); + cob.invokeinterface(CD_Iterator, "next", MTD_ITERATOR_NEXT); + cob.checkcast(CD_JsonValue); + final int valueSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(valueSlot); + cob.aload(valueSlot); + cob.aload(1); + cob.aload(2); + cob.invokestatic(self, callTarget, MTD_CONT); + cob.goto_(loopStart); + cob.labelBinding(loopEnd); + cob.goto_(objectDone); + + // Array elements + cob.labelBinding(arrayLabel); + cob.aload(0); + cob.instanceOf(CD_JsonArray); + cob.ifeq(done); + final int listSlot = emitAsList(cob); + final int sizeSlot = emitListSize(cob, listSlot); + final int iSlot = cob.allocateLocal(TypeKind.INT); + final var elementLoopStart = cob.newLabel(); + final var elementLoopEnd = cob.newLabel(); + cob.iconst_0(); + cob.istore(iSlot); + cob.labelBinding(elementLoopStart); + cob.iload(iSlot); + cob.iload(sizeSlot); + cob.if_icmpge(elementLoopEnd); + cob.aload(listSlot); + cob.iload(iSlot); + cob.invokeinterface(CD_List, "get", MTD_OBJECT_INT); + cob.checkcast(CD_JsonValue); + final int elementSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(elementSlot); + cob.aload(elementSlot); + cob.aload(1); + cob.aload(2); + cob.invokestatic(self, callTarget, MTD_CONT); + cob.iinc(iSlot, 1); + cob.goto_(elementLoopStart); + cob.labelBinding(elementLoopEnd); + cob.labelBinding(objectDone); + } + + /// Matches a slice by start:end:step, mirroring the interpreter's + /// normalization and clamping rules exactly. + private void emitSlice(CodeBuilder cob, int k, Integer start, Integer end, Integer step, Label done) { + final int stepValue = step != null ? step : 1; + cob.aload(0); + cob.instanceOf(CD_JsonArray); + cob.ifeq(done); + final int listSlot = emitAsList(cob); + final int sizeSlot = emitListSize(cob, listSlot); + if (stepValue == 0) { + return; // invalid step: no matches, like the interpreter + } + final int startSlot = cob.allocateLocal(TypeKind.INT); + final int endSlot = cob.allocateLocal(TypeKind.INT); + final int iSlot = cob.allocateLocal(TypeKind.INT); + final var positiveLabel = cob.newLabel(); + final var negativeLabel = cob.newLabel(); + final var afterLabel = cob.newLabel(); + cob.ldc(stepValue); + cob.ifgt(positiveLabel); + cob.goto_(negativeLabel); + + cob.labelBinding(positiveLabel); + emitForwardSlice(cob, k, listSlot, sizeSlot, start, end, stepValue, startSlot, endSlot, iSlot); + cob.goto_(afterLabel); + + cob.labelBinding(negativeLabel); + emitBackwardSlice(cob, k, listSlot, sizeSlot, start, end, stepValue, startSlot, endSlot, iSlot); + + cob.labelBinding(afterLabel); + } + + private void emitForwardSlice(CodeBuilder cob, int k, int listSlot, int sizeSlot, + Integer start, Integer end, int stepValue, + int startSlot, int endSlot, int iSlot) { + // start = (start != null) ? normalize(start, size) : 0 + emitOptionalBound(cob, start, sizeSlot, FALLBACK_ZERO, startSlot); + emitOptionalBound(cob, end, sizeSlot, FALLBACK_SIZE, endSlot); + clampLowHigh(cob, startSlot, 0, null, sizeSlot); + clampLowHigh(cob, endSlot, 0, null, sizeSlot); + final var loopStart = cob.newLabel(); + final var loopEnd = cob.newLabel(); + cob.iload(startSlot); + cob.istore(iSlot); + cob.labelBinding(loopStart); + cob.iload(iSlot); + cob.iload(endSlot); + cob.if_icmpge(loopEnd); + emitSliceElement(cob, k, listSlot, iSlot); + cob.iinc(iSlot, stepValue); + cob.goto_(loopStart); + cob.labelBinding(loopEnd); + } + + private void emitBackwardSlice(CodeBuilder cob, int k, int listSlot, int sizeSlot, + Integer start, Integer end, int stepValue, + int startSlot, int endSlot, int iSlot) { + // start = (start != null) ? normalize(start, size) : size - 1 + emitOptionalBound(cob, start, sizeSlot, FALLBACK_SIZE_MINUS_ONE, startSlot); + emitOptionalBound(cob, end, sizeSlot, FALLBACK_MINUS_ONE, endSlot); + // start = Math.max(0, Math.min(start, size - 1)) + cob.iload(startSlot); + cob.iload(sizeSlot); + cob.iconst_1(); + cob.isub(); + cob.invokestatic(CD_Math, "min", MTD_II_I); + cob.ldc(0); + cob.invokestatic(CD_Math, "max", MTD_II_I); + cob.istore(startSlot); + final var loopStart = cob.newLabel(); + final var loopEnd = cob.newLabel(); + cob.iload(startSlot); + cob.istore(iSlot); + cob.labelBinding(loopStart); + cob.iload(iSlot); + cob.iload(endSlot); + cob.if_icmple(loopEnd); + emitSliceElement(cob, k, listSlot, iSlot); + cob.iinc(iSlot, stepValue); + cob.goto_(loopStart); + cob.labelBinding(loopEnd); + } + + /// Fallback kinds for slice bounds that the interpreter computes at runtime. + private static final int FALLBACK_ZERO = 0; + private static final int FALLBACK_SIZE = 1; + private static final int FALLBACK_SIZE_MINUS_ONE = 2; + private static final int FALLBACK_MINUS_ONE = 3; + + /// target = (bound != null) ? normalizeIndex(bound, size) : fallback(size) + private void emitOptionalBound(CodeBuilder cob, Integer bound, int sizeSlot, int fallbackKind, int targetSlot) { + if (bound != null) { + cob.ldc(bound); + cob.iload(sizeSlot); + cob.invokestatic(CD_Helpers, "normalizeIndex", MTD_II_I); + } else { + switch (fallbackKind) { + case FALLBACK_ZERO -> cob.ldc(0); + case FALLBACK_SIZE -> cob.iload(sizeSlot); + case FALLBACK_SIZE_MINUS_ONE -> { + cob.iload(sizeSlot); + cob.iconst_1(); + cob.isub(); + } + case FALLBACK_MINUS_ONE -> cob.ldc(-1); + default -> throw new IllegalArgumentException("unknown fallback kind: " + fallbackKind); + } + } + cob.istore(targetSlot); + } + + /// slot = Math.max(low, Math.min(slot, high)) where high is either another + /// int local (highSlot >= 0) or a constant (high). + private static void clampLowHigh(CodeBuilder cob, int slot, int low, Integer high, int highSlot) { + cob.iload(slot); + if (highSlot >= 0) { + cob.iload(highSlot); + } else { + cob.ldc(high); + } + cob.invokestatic(CD_Math, "min", MTD_II_I); + cob.ldc(low); + cob.invokestatic(CD_Math, "max", MTD_II_I); + cob.istore(slot); + } + + private void emitSliceElement(CodeBuilder cob, int k, int listSlot, int iSlot) { + cob.aload(listSlot); + cob.iload(iSlot); + cob.invokeinterface(CD_List, "get", MTD_OBJECT_INT); + cob.checkcast(CD_JsonValue); + final int elementSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(elementSlot); + emitContinueWith(cob, k, elementSlot); + } + + /// Filter loop: for each array element, run the generated predicate and + /// continue with matching elements. + private void emitFilterLoop(CodeBuilder cob, int k, int listSlot, int predMethod) { + final int sizeSlot = emitListSize(cob, listSlot); + final int iSlot = cob.allocateLocal(TypeKind.INT); + final var loopStart = cob.newLabel(); + final var loopEnd = cob.newLabel(); + final var continueLabel = cob.newLabel(); + cob.iconst_0(); + cob.istore(iSlot); + cob.labelBinding(loopStart); + cob.iload(iSlot); + cob.iload(sizeSlot); + cob.if_icmpge(loopEnd); + cob.aload(listSlot); + cob.iload(iSlot); + cob.invokeinterface(CD_List, "get", MTD_OBJECT_INT); + cob.checkcast(CD_JsonValue); + final int elementSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(elementSlot); + cob.aload(elementSlot); + cob.invokestatic(self, "pred" + predMethod, MTD_PRED); + cob.ifeq(continueLabel); + emitContinueWith(cob, k, elementSlot); + cob.labelBinding(continueLabel); + cob.iinc(iSlot, 1); + cob.goto_(loopStart); + cob.labelBinding(loopEnd); + } + + /// Limited script support: emits the last element for "(@.length-1)"; + /// any other script logs once through the shared helper, mirroring the interpreter. + private void emitScriptExpression(CodeBuilder cob, int k, String script, Label done) { + cob.aload(0); + cob.instanceOf(CD_JsonArray); + cob.ifeq(done); + final int listSlot = emitAsList(cob); + final int sizeSlot = emitListSize(cob, listSlot); + if ("@.length-1".equals(script)) { + final int lastIndexSlot = cob.allocateLocal(TypeKind.INT); + cob.iload(sizeSlot); + cob.iconst_1(); + cob.isub(); + cob.istore(lastIndexSlot); + cob.iload(lastIndexSlot); + cob.iflt(done); + cob.aload(listSlot); + cob.iload(lastIndexSlot); + cob.invokeinterface(CD_List, "get", MTD_OBJECT_INT); + cob.checkcast(CD_JsonValue); + final int elementSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(elementSlot); + emitContinueWith(cob, k, elementSlot); + } else { + cob.ldc(script); + cob.invokestatic(CD_Helpers, "unsupportedScript", MTD_VOID_STRING); + } + } + + /// Recursive descent: applies the target at the current level and then + /// walks every descendant, exactly like the interpreter. + private void emitRecursiveDescent(int k, JsonPathAst.Segment target) { + emitApplyTarget(k, target); + clb.withMethodBody("desc" + k, MTD_CONT, ClassFile.ACC_PRIVATE | ClassFile.ACC_STATIC, cob -> { + cob.aload(0); + cob.aload(1); + cob.aload(2); + cob.invokestatic(self, "applyTarget" + k, MTD_CONT); + final var done = cob.newLabel(); + emitWalkChildren(cob, "desc" + k, done); + cob.labelBinding(done); + cob.return_(); + }); + } + + /// Mirrors the interpreter's recursive-descent target handling: property + /// access, wildcard, and array index targets match; anything else logs once. + private void emitApplyTarget(int k, JsonPathAst.Segment target) { + clb.withMethodBody("applyTarget" + k, MTD_CONT, ClassFile.ACC_PRIVATE | ClassFile.ACC_STATIC, cob -> { + final var done = cob.newLabel(); + switch (target) { + case JsonPathAst.PropertyAccess(String name) -> + emitPropertyMatch(cob, k, name, done); + case JsonPathAst.Wildcard ignored -> + emitChildren(cob, k, done); + case JsonPathAst.ArrayIndex(int index) -> + emitIndexMatch(cob, k, index, done); + default -> + LOG.finer(() -> "Unsupported target in recursive descent: " + target); + } + cob.labelBinding(done); + cob.return_(); + }); + } + + // -- filter predicate emission -- + + private int predicateMethodFor(JsonPathAst.FilterExpression expression) { + final var existing = predicateMethods.get(expression); + if (existing != null) { + return existing; + } + final int method = predicateMethods.size(); + predicateMethods.put(expression, method); + emitPredicate(expression, method); + return method; + } + + private void emitPredicate(JsonPathAst.FilterExpression expression, int method) { + clb.withMethodBody("pred" + method, MTD_PRED, ClassFile.ACC_PRIVATE | ClassFile.ACC_STATIC, cob -> { + switch (expression) { + case JsonPathAst.ExistsFilter(JsonPathAst.PropertyPath path) -> { + cob.aload(0); // the candidate node + cob.getstatic(self, "P" + pathConstant(path.properties()), CD_List); + cob.invokestatic(CD_Helpers, "resolvePropertyPath", MTD_RESOLVE_PATH); + cob.instanceOf(CD_JsonValue); // false for null: value must exist + cob.ireturn(); + } + case JsonPathAst.ComparisonFilter(var left, var op, var right) -> { + emitFilterOperand(cob, left); + cob.getstatic(CD_ComparisonOp, op.name(), CD_ComparisonOp); + emitFilterOperand(cob, right); + cob.invokestatic(CD_Helpers, "compareValues", MTD_COMPARE); + cob.ireturn(); + } + case JsonPathAst.LogicalFilter(var left, var op, var right) -> { + final int leftMethod = predicateMethodFor(left); + switch (op) { + case AND -> { + final int rightMethod = predicateMethodFor(right); + final var falseLabel = cob.newLabel(); + cob.aload(0); + cob.invokestatic(self, "pred" + leftMethod, MTD_PRED); + cob.ifeq(falseLabel); + cob.aload(0); + cob.invokestatic(self, "pred" + rightMethod, MTD_PRED); + cob.ireturn(); + cob.labelBinding(falseLabel); + cob.iconst_0(); + cob.ireturn(); + } + case OR -> { + final int rightMethod = predicateMethodFor(right); + final var trueLabel = cob.newLabel(); + final var falseLabel = cob.newLabel(); + cob.aload(0); + cob.invokestatic(self, "pred" + leftMethod, MTD_PRED); + cob.ifne(trueLabel); + cob.aload(0); + cob.invokestatic(self, "pred" + rightMethod, MTD_PRED); + cob.ifeq(falseLabel); + cob.labelBinding(trueLabel); + cob.iconst_1(); + cob.ireturn(); + cob.labelBinding(falseLabel); + cob.iconst_0(); + cob.ireturn(); + } + case NOT -> { + final var falseLabel = cob.newLabel(); + cob.aload(0); + cob.invokestatic(self, "pred" + leftMethod, MTD_PRED); + cob.ifne(falseLabel); + cob.iconst_1(); + cob.ireturn(); + cob.labelBinding(falseLabel); + cob.iconst_0(); + cob.ireturn(); + } + } + } + case JsonPathAst.CurrentNode ignored -> { + cob.iconst_1(); + cob.ireturn(); + } + case JsonPathAst.PropertyPath path -> { + cob.aload(0); + cob.getstatic(self, "P" + pathConstant(path.properties()), CD_List); + cob.invokestatic(CD_Helpers, "resolvePropertyPath", MTD_RESOLVE_PATH); + cob.instanceOf(CD_JsonValue); + cob.ireturn(); + } + case JsonPathAst.LiteralValue ignored -> { + cob.iconst_1(); // mirrors the interpreter: bare literals match + cob.ireturn(); + } + } + }); + } + + /// Pushes the comparable operand for a filter expression onto the stack, + /// mirroring the interpreter's resolveFilterExpression. + private void emitFilterOperand(CodeBuilder cob, JsonPathAst.FilterExpression operand) { + switch (operand) { + case JsonPathAst.PropertyPath path -> { + cob.aload(0); + cob.getstatic(self, "P" + pathConstant(path.properties()), CD_List); + cob.invokestatic(CD_Helpers, "resolvePropertyPath", MTD_RESOLVE_PATH); + cob.invokestatic(CD_Helpers, "toJsonComparable", MTD_TO_COMPARABLE); + } + case JsonPathAst.LiteralValue(Object value) -> emitLiteral(cob, value); + case JsonPathAst.CurrentNode ignored -> { + cob.aload(0); + cob.invokestatic(CD_Helpers, "toJsonComparable", MTD_TO_COMPARABLE); + } + default -> cob.aconst_null(); + } + } + + /// Pushes a boxed filter literal (String, Boolean, Long, Double, or JSON null). + private static void emitLiteral(CodeBuilder cob, Object value) { + switch (value) { + case null -> cob.aconst_null(); + case String s -> cob.ldc(s); + case Boolean b -> cob.getstatic(ConstantDescs.CD_Boolean, b ? "TRUE" : "FALSE", ConstantDescs.CD_Boolean); + case Integer i -> { + cob.ldc(i); + cob.invokestatic(ConstantDescs.CD_Integer, "valueOf", MTD_INTEGER_VALUE_OF); + } + case Long l -> { + cob.ldc(l); + cob.invokestatic(ConstantDescs.CD_Long, "valueOf", MTD_LONG_VALUE_OF); + } + case Double d -> { + cob.ldc(d); + cob.invokestatic(ConstantDescs.CD_Double, "valueOf", MTD_DOUBLE_VALUE_OF); + } + case Float f -> { + cob.ldc(f); + cob.invokestatic(ConstantDescs.CD_Float, "valueOf", MTD_FLOAT_VALUE_OF); + } + default -> throw new IllegalArgumentException( + "unsupported filter literal type: " + value.getClass()); + } + } + + // -- shared bytecode helpers for the emitted code -- + + /// current.asList() of the JsonArray in local slot 0, stored in a fresh local. + private static int emitAsList(CodeBuilder cob) { + cob.aload(0); + cob.checkcast(CD_JsonArray); + cob.invokeinterface(CD_JsonArray, "asList", MTD_LIST); + final int listSlot = cob.allocateLocal(TypeKind.REFERENCE); + cob.astore(listSlot); + return listSlot; + } + + private static int emitListSize(CodeBuilder cob, int listSlot) { + cob.aload(listSlot); + cob.invokeinterface(CD_List, "size", MTD_INT); + final int sizeSlot = cob.allocateLocal(TypeKind.INT); + cob.istore(sizeSlot); + return sizeSlot; + } + + /// Returns (and registers) the constant-list field index for a property path. + private int pathConstant(List properties) { + final var canonical = List.copyOf(properties); + final var existing = pathConstants.get(canonical); + if (existing != null) { + return existing; + } + final int index = pathConstants.size(); + pathConstants.put(canonical, index); + return index; + } + + /// Emits the private static final List fields holding shared property paths, + /// initialized in once every user of them has been emitted. + private void emitPathConstantFields() { + for (final var entry : pathConstants.entrySet()) { + clb.withField("P" + entry.getValue(), CD_List, + ClassFile.ACC_PRIVATE | ClassFile.ACC_STATIC | ClassFile.ACC_FINAL); + } + clb.withMethodBody(ConstantDescs.CLASS_INIT_NAME, ConstantDescs.MTD_void, ClassFile.ACC_STATIC, cob -> { + for (final var entry : pathConstants.entrySet()) { + final var properties = entry.getKey(); + cob.ldc(properties.size()); + cob.anewarray(ConstantDescs.CD_String); + for (int i = 0; i < properties.size(); i++) { + cob.dup(); + cob.ldc(i); + cob.ldc(properties.get(i)); + cob.aastore(); + } + cob.invokestatic(CD_Arrays, "asList", MTD_ARRAYS_AS_LIST); + cob.putstatic(self, "P" + entry.getValue(), CD_List); + } + cob.return_(); + }); + } +} diff --git a/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCodegen.java b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCodegen.java new file mode 100644 index 00000000..558a41f9 --- /dev/null +++ b/json-java21-jsonpath/src/main/java/json/java21/jsonpath/JsonPathCodegen.java @@ -0,0 +1,78 @@ +package json.java21.jsonpath; + +import java.lang.invoke.MethodHandles; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Logger; + +/// Compiles a JsonPath AST into a bytecode-generated [JsonPath]. +/// +/// The generated class targets Java 21 (class file version 65, +/// `ClassFile.JAVA_21_VERSION`) and is produced with the JDK 24 ClassFile +/// API (JEP 484), mirroring `JtdCodegen` / `JtdValidator.compileGenerated` +/// in the jtd-codegen module. This class is only present in artifacts built +/// on JDK 24+; the interpreted engine is always available. +/// +/// Use [JsonPathCodegen#compile(JsonPath)] for an on-demand compiled +/// query, or [JsonPathCodegen#compileBytes(String, JsonPathAst.Root)] +/// for ahead-of-time, `jtd2jar`-style build-time tooling. +public final class JsonPathCodegen { + + static final Logger LOG = Logger.getLogger(JsonPathCodegen.class.getName()); + private static final AtomicLong COUNTER = new AtomicLong(); + private static final String PACKAGE_NAME = "json.java21.jsonpath"; + + private JsonPathCodegen() {} + + /// Result of compilation including the compiled path and generated class statistics. + public record CompileResult(JsonPath path, int classfileBytes) {} + + /// Compiles a parsed JsonPath into a bytecode-generated query. + /// Requires JDK 24+ (ClassFile API, JEP 484). Generated classes target Java 21 bytecode. + /// + /// @param path the parsed JsonPath (interpreted or compiled; compiled paths return unchanged) + /// @return a reusable compiled [JsonPath] implementing the same public surface + public static JsonPath compile(JsonPath path) { + return compileWithStats(path).path(); + } + + /// Compiles the path and returns both the compiled path and the generated + /// classfile size in bytes. Useful for benchmarking and diagnostics. + /// + /// @param path the parsed JsonPath + /// @return the compiled path and the generated classfile size in bytes + public static CompileResult compileWithStats(JsonPath path) { + return switch (path) { + case JsonPathCompiled compiled -> new CompileResult(compiled, 0); + case JsonPathInterpreted interpreted -> compileInterpreted(interpreted); + }; + } + + /// Emits the classfile bytes for a query without loading it. + /// + /// For ahead-of-time, `jtd2jar`-style build-time tooling. Generated classes are + /// always emitted in the `json.java21.jsonpath` package so they can implement + /// the package-private [JsonPathExecutor] interface; the classfile targets + /// Java 21 bytecode (`ClassFile.JAVA_21_VERSION`). + /// + /// @param className simple name for the generated executor class (package-fixed) + /// @param ast the parsed JsonPath AST to compile + /// @return the generated classfile bytes + public static byte[] compileBytes(String className, JsonPathAst.Root ast) { + return JsonPathBytecodeEmitter.emit(PACKAGE_NAME, className, ast); + } + + private static CompileResult compileInterpreted(JsonPathInterpreted interpreted) { + final var className = "GeneratedJsonPath" + COUNTER.incrementAndGet(); + final var ast = interpreted.ast(); + LOG.fine(() -> "Generating JsonPath executor class: " + PACKAGE_NAME + "." + className); + + final var bytes = compileBytes(className, ast); + try { + final var clazz = MethodHandles.lookup().defineClass(bytes); + final var executor = (JsonPathExecutor) clazz.getDeclaredConstructor().newInstance(); + return new CompileResult(new JsonPathCompiled(ast, executor, interpreted.toString()), bytes.length); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Failed to load generated JsonPath executor: " + className, e); + } + } +} diff --git a/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCodegenTest.java b/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCodegenTest.java new file mode 100644 index 00000000..a11ab788 --- /dev/null +++ b/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCodegenTest.java @@ -0,0 +1,80 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.Json; +import jdk.incubator.java.util.json.JsonValue; +import org.junit.jupiter.api.Test; + +import java.util.logging.Logger; + +import static org.assertj.core.api.Assertions.assertThat; + +/// Tests for JsonPathCodegen mechanics: compilation produces a compiled engine +/// facade wrapping a runtime-generated executor, emits Java 21 bytecode, is +/// idempotent, and exposes ahead-of-time classfile bytes for jtd2jar-style tooling. +class JsonPathCodegenTest extends JsonPathLoggingConfig { + + private static final Logger LOG = Logger.getLogger(JsonPathCodegenTest.class.getName()); + + private static final String DOC_JSON = """ + {"store": {"bicycle": {"color": "red"}}} + """; + + @Test + void compileReturnsCompiledEngineFacade() { + LOG.info(() -> "TEST: compileReturnsCompiledEngineFacade"); + final var path = JsonPathCodegen.compile(JsonPath.parse("$.store.bicycle.color")); + assertThat(path).isInstanceOf(JsonPathCompiled.class); + assertThat(path.isCompiled()).isTrue(); + assertThat(path.isInterpreted()).isFalse(); + } + + @Test + void compiledEngineQueriesDocuments() { + LOG.info(() -> "TEST: compiledEngineQueriesDocuments"); + final var document = Json.parse(DOC_JSON); + final var path = JsonPathCodegen.compile(JsonPath.parse("$.store.bicycle.color")); + final var results = path.query(document); + assertThat(results).hasSize(1); + assertThat(((jdk.incubator.java.util.json.JsonString) results.getFirst()).asString()).isEqualTo("red"); + } + + @Test + void compileIsIdempotent() { + LOG.info(() -> "TEST: compileIsIdempotent - compiling a compiled path returns the same instance"); + final var path = JsonPathCodegen.compile(JsonPath.parse("$.store")); + assertThat(JsonPathCodegen.compile(path)).isSameAs(path); + } + + @Test + void compiledEnginePreservesPathTextAndAst() { + LOG.info(() -> "TEST: compiledEnginePreservesPathTextAndAst"); + final var interpreted = JsonPath.parse("$.store.book"); + final var compiled = JsonPathCodegen.compile(interpreted); + assertThat(compiled.toString()).isEqualTo(interpreted.toString()); + assertThat(compiled.ast()).isNotNull(); + assertThat(compiled.ast().segments()).hasSize(2); + } + + @Test + void compileBytesEmitsJava21Classfile() { + LOG.info(() -> "TEST: compileBytesEmitsJava21Classfile - classfile major version must be 65 (Java 21)"); + final var ast = JsonPathParser.parse("$.store.bicycle.color"); + final var bytes = JsonPathCodegen.compileBytes("GeneratedForVersionProbe", ast); + assertThat(bytes).isNotEmpty(); + final int minor = ((bytes[4] & 0xFF) << 8) | (bytes[5] & 0xFF); + final int major = ((bytes[6] & 0xFF) << 8) | (bytes[7] & 0xFF); + LOG.fine(() -> "Generated classfile version: " + major + "." + minor); + assertThat(major).isEqualTo(65); // ClassFile.JAVA_21_VERSION + assertThat(minor).isZero(); + } + + @Test + void compileBytesEmitsFreshClassesForDistinctAsts() { + LOG.info(() -> "TEST: compileBytesEmitsFreshClassesForDistinctAsts"); + final var bytesA = JsonPathCodegen.compileBytes("ProbeA", JsonPathParser.parse("$.a")); + final var bytesB = JsonPathCodegen.compileBytes("ProbeA", JsonPathParser.parse("$.a.b")); + assertThat(bytesA).isNotEmpty(); + assertThat(bytesB).isNotEmpty(); + assertThat(bytesA).isNotEqualTo(bytesB); + } +} diff --git a/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCompilerParityTest.java b/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCompilerParityTest.java new file mode 100644 index 00000000..6561734b --- /dev/null +++ b/json-java21-jsonpath/src/test/java/json/java21/jsonpath/JsonPathCompilerParityTest.java @@ -0,0 +1,180 @@ +package json.java21.jsonpath; + +import jdk.incubator.java.util.json.Json; +import jdk.incubator.java.util.json.JsonValue; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.logging.Logger; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +/// Parity tests for the interpreted and bytecode-generated JsonPath engines. +/// +/// Every expression in the module's existing test corpus runs against a set of +/// documents through both engines; the compiled engine's results must be +/// element-for-element identical to the interpreted engine's results. +/// This is the contract documented in the module README ("Two Engines"). +class JsonPathCompilerParityTest extends JsonPathLoggingConfig { + + private static final Logger LOG = Logger.getLogger(JsonPathCompilerParityTest.class.getName()); + + private static final String STORE_JSON = """ + { + "store": { + "book": [ + { + "category": "reference", + "author": "Nigel Rees", + "title": "Sayings of the Century", + "price": 8.95 + }, + { + "category": "fiction", + "author": "Evelyn Waugh", + "title": "Sword of Honour", + "price": 12.99 + }, + { + "category": "fiction", + "author": "Herman Melville", + "title": "Moby Dick", + "isbn": "0-553-21311-3", + "price": 8.99 + }, + { + "category": "fiction", + "author": "J. R. R. Tolkien", + "title": "The Lord of the Rings", + "isbn": "0-395-19395-8", + "price": 22.99 + } + ], + "bicycle": { + "color": "red", + "price": 19.95 + } + } + } + """; + + private static final String NUMBERS_JSON = """ + {"numbers": [3, 1, 4, 1, 5, 9, 2, 6], "nested": {"numbers": [7]}} + """; + + private static final String EMPTY_JSON = """ + {"empty": [], "nullobject": null, "text": "hello"} + """; + + private static List documents() { + return List.of( + Json.parse(STORE_JSON), + Json.parse(NUMBERS_JSON), + Json.parse(EMPTY_JSON), + Json.parse("42"), + Json.parse("[1, 2, 3]"), + Json.parse("{}")); + } + + /// The full expression corpus reused from the existing JsonPath test catalogue. + static Stream expressions() { + return Stream.of( + // root and property access + "$", + "$.store", + "$.store.bicycle", + "$.store.bicycle.color", + "$['store']['book']", + "$.nonexistent", + "$['special-key']", + // array indices + "$.store.book[0]", + "$.store.book[3]", + "$.store.book[-1]", + "$.store.book[100]", + "$.store.book[0].title", + "$.numbers[2]", + "$.numbers[-9]", + // slices + "$.store.book[:2]", + "$.store.book[0:4:2]", + "$.store.book[::-1]", + "$.store.book[-1:]", + "$.store.book[1:]", + "$.store.book[::2]", + "$.store.book[10:20]", + "$.numbers[:3]", + "$.numbers[::-2]", + // wildcards + "$.store.*", + "$.store.book[*]", + "$.store.book[*].author", + "$.numbers[*]", + "$[*]", + "$.*", + // filters + "$.store.book[?(@.isbn)]", + "$.store.book[?(!@.isbn)]", + "$.store.book[?(@.price<10)]", + "$.store.book[?(@.price > 20)]", + "$.store.book[?(@.category=='fiction')]", + "$.store.book[?(@.category!=\"reference\")]", + "$.store.book[?(@.price<=12.99)]", + "$.store.book[?(@.price>=8.95)]", + "$.store.book[?(@.isbn && @.price>20)]", + "$.store.book[?(@.price<10 || @.price>20)]", + "$.store.book[?(@.isbn && (@.price<10 || @.price>20))]", + "$.store.book[?(@)]", + "$..book[?(@.price>20)]", + "$..book[?(@.price<10)]", + "$.store.book[?(@.title=='Moby Dick')].price", + // unions + "$.store.book[0,1]", + "$.store.book[3,0]", + "$.store['book','bicycle']", + "$.store['color','bicycle']", + "$..book[0,1]", + // recursive descent + "$..author", + "$..price", + "$..*", + "$..book[2]", + "$.store..price", + "$..book[0,1].title", + "$..book[-1]", + "$..book[(@.length-1)]", + "$..book[:2].title", + "$.store.book[(@.length-1)].title", + // unsupported/edge script and odd targets: results must still match + "$.store.book[(@.length)]", + // scalars and empty documents + "$.text", + "$.empty", + "$.empty[*]", + "$.numbers.nested"); + } + + @ParameterizedTest + @MethodSource("expressions") + void interpretedAndGeneratedEnginesProduceIdenticalResults(String pathExpression) { + LOG.info(() -> "TEST: interpretedAndGeneratedEnginesProduceIdenticalResults - " + pathExpression); + for (final var document : documents()) { + final var interpreted = JsonPath.parse(pathExpression); + final var compiled = JsonPathCodegen.compile(interpreted); + assertThat(compiled).isInstanceOf(JsonPathCompiled.class); + + final var interpretedResults = interpreted.query(document); + final var compiledResults = compiled.query(document); + + LOG.fine(() -> "Path: " + pathExpression + + " | interpreted results: " + interpretedResults + + " | compiled results: " + compiledResults); + + assertThat(compiledResults) + .as("Compiled results for '%s' should match interpreted results", pathExpression) + .containsExactlyElementsOf(interpretedResults); + } + } +} From 2edffd4335623e7c4750e04490c7954dc4703330 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:14:42 +0000 Subject: [PATCH 6/7] Issue #178: keep the ClassFile API codegen sources invisible to javadoc on JDK 21 CI's JDK 21 build failed in maven-javadoc-plugin because javadoc completes each documented package by re-scanning -sourcepath, which re-read the ClassFile API sources even though sourceFileExcludes removed them from the file list ('package java.lang.classfile does not exist'). The module now points -sourcepath at a placeholder path so nothing extra is scanned on JDK 21; the JDK 24+ jsonpath-codegen profile overrides the excludes and sets release 24 so the compiled-engine classes stay documentable there (matching the jtd-codegen parent profile convention). To verify: with JDK 21, mvn -pl json-java21-jsonpath clean package -DskipTests (attach-javadocs included) and mvn -pl json-java21-jsonpath test (100 tests green); with JDK 24+, mvn -pl json-java21-jsonpath test (170 tests green). --- json-java21-jsonpath/pom.xml | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/json-java21-jsonpath/pom.xml b/json-java21-jsonpath/pom.xml index 3b96b9ba..7a176f67 100644 --- a/json-java21-jsonpath/pom.xml +++ b/json-java21-jsonpath/pom.xml @@ -107,8 +107,14 @@ org.apache.maven.plugins maven-javadoc-plugin - + + ${project.build.directory}/javadoc21-sourcepath-placeholder json/java21/jsonpath/JsonPathCodegen.java json/java21/jsonpath/JsonPathBytecodeEmitter.java @@ -169,10 +175,11 @@ org.apache.maven.plugins maven-javadoc-plugin - - json/java21/jsonpath/JsonPathCodegen.java - json/java21/jsonpath/JsonPathBytecodeEmitter.java - + + 24 + From e49eebc4048cb3b671a5a1fc2c2ea64634182123 Mon Sep 17 00:00:00 2001 From: Simon Massey <322608+simbo1905@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:16:51 +0000 Subject: [PATCH 7/7] Issue #178: bump CI pinned test count for the 70 new parity and codegen tests The build job asserts total test counts to catch silently skipped tests. 2038 -> 2108 (64 parity + 6 codegen tests added by this issue). --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52d00aff..dcec1370 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: for k in totals: totals[k]+=int(r.get(k,'0')) except Exception: pass - exp_tests=2038 + exp_tests=2108 exp_skipped=0 if totals['tests']!=exp_tests or totals['skipped']!=exp_skipped: print(f"Unexpected test totals: {totals} != expected tests={exp_tests}, skipped={exp_skipped}")