From 0f7ddf48586365a600693ca05b199a080e2ad02c Mon Sep 17 00:00:00 2001 From: siddartha siddu Date: Wed, 25 Nov 2026 06:53:59 +0530 Subject: [PATCH] perf: index fixed string lists in the in operator Build a membership index for lists of at least 16 string literals so repeated evaluations can reuse it. Discard the index when an iterator or sublist can mutate the parsed list. Cover localized error paths, custom operations, missing codes, and edits to parsed rules. --- .../jsonlogic/ast/JsonLogicArray.java | 42 +++++- .../jsonlogic/ast/JsonLogicParser.java | 3 + .../evaluator/expressions/InExpression.java | 27 ++++ .../PreEvaluatedArgumentsExpression.java | 9 +- .../jamsesso/jsonlogic/InExpressionTests.java | 133 ++++++++++++++++++ 5 files changed, 207 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicArray.java b/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicArray.java index cdb7949..5b68917 100644 --- a/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicArray.java +++ b/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicArray.java @@ -1,17 +1,51 @@ package io.github.jamsesso.jsonlogic.ast; import java.util.Collection; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import java.util.Set; public class JsonLogicArray implements JsonLogicNode, List { private final List delegate; + private volatile Set stringIndex; public JsonLogicArray(List delegate) { this.delegate = delegate; } + void indexStringLiterals() { + if (delegate.size() < 16) { + return; + } + Set strings = new HashSet<>(); + for (JsonLogicNode node : delegate) { + if (!(node instanceof JsonLogicString)) { + return; + } + strings.add(((JsonLogicString) node).getValue()); + } + stringIndex = strings; + } + + /** Returns null when membership requires evaluating the array normally. */ + public Boolean indexedStringMatch(Object value) { + Set index = stringIndex; + if (index == null || (value != null && !(value instanceof String))) { + return null; + } + return index.contains(value); + } + + private List mutableView() { + // An iterator or sublist can change the literals after it has been returned. + if (stringIndex != null) { + stringIndex = null; + } + return delegate; + } + @Override public JsonLogicNodeType getType() { return JsonLogicNodeType.ARRAY; @@ -34,7 +68,7 @@ public boolean contains(Object o) { @Override public Iterator iterator() { - return delegate.iterator(); + return mutableView().iterator(); } @Override @@ -119,16 +153,16 @@ public int lastIndexOf(Object o) { @Override public ListIterator listIterator() { - return delegate.listIterator(); + return mutableView().listIterator(); } @Override public ListIterator listIterator(int index) { - return delegate.listIterator(index); + return mutableView().listIterator(index); } @Override public List subList(int fromIndex, int toIndex) { - return delegate.subList(fromIndex, toIndex); + return mutableView().subList(fromIndex, toIndex); } } diff --git a/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicParser.java b/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicParser.java index bf442b8..063e673 100644 --- a/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicParser.java +++ b/src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicParser.java @@ -90,6 +90,9 @@ private static JsonLogicNode parse(JsonElement root, String jsonPath) throws Jso } // Handle regular operations + if ("in".equals(key) && arguments.size() == 2 && arguments.get(1) instanceof JsonLogicArray) { + ((JsonLogicArray) arguments.get(1)).indexStringLiterals(); + } return new JsonLogicOperation(key, arguments); } } diff --git a/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/InExpression.java b/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/InExpression.java index e5f6d0b..d1e7bb1 100644 --- a/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/InExpression.java +++ b/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/InExpression.java @@ -1,8 +1,12 @@ package io.github.jamsesso.jsonlogic.evaluator.expressions; +import io.github.jamsesso.jsonlogic.ast.JsonLogicArray; +import io.github.jamsesso.jsonlogic.ast.JsonLogicNode; import io.github.jamsesso.jsonlogic.evaluator.JsonLogicEvaluationException; +import io.github.jamsesso.jsonlogic.evaluator.JsonLogicEvaluator; import io.github.jamsesso.jsonlogic.utils.ArrayLike; +import java.util.ArrayList; import java.util.List; public class InExpression implements PreEvaluatedArgumentsExpression { @@ -17,6 +21,29 @@ public String key() { return "in"; } + @Override + public Object evaluate(JsonLogicEvaluator evaluator, JsonLogicArray arguments, Object data, String jsonPath) + throws JsonLogicEvaluationException { + if (evaluator.getClass() != JsonLogicEvaluator.class) { + return PreEvaluatedArgumentsExpression.super.evaluate(evaluator, arguments, data, jsonPath); + } + List values = new ArrayList<>(arguments.size()); + Boolean indexedMatch = null; + int index = 0; + for (JsonLogicNode argument : arguments) { + String path = String.format("%s[%d]", jsonPath, index++); + if (index == 2 && argument != null && argument.getClass() == JsonLogicArray.class) { + indexedMatch = ((JsonLogicArray) argument).indexedStringMatch(values.get(0)); + if (indexedMatch != null) { + continue; + } + } + values.add(evaluator.evaluate(argument, data, path)); + } + return indexedMatch != null ? indexedMatch + : evaluate(PreEvaluatedArgumentsExpression.unpackArguments(values), data, jsonPath); + } + @Override public Object evaluate(List arguments, Object data, String jsonPath) throws JsonLogicEvaluationException { if (arguments.size() < 2) { diff --git a/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/PreEvaluatedArgumentsExpression.java b/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/PreEvaluatedArgumentsExpression.java index 26adfe4..f56abc2 100644 --- a/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/PreEvaluatedArgumentsExpression.java +++ b/src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/PreEvaluatedArgumentsExpression.java @@ -16,10 +16,13 @@ default Object evaluate(JsonLogicEvaluator evaluator, JsonLogicArray arguments, throws JsonLogicEvaluationException { List values = evaluator.evaluate(arguments, data, jsonPath); + return evaluate(unpackArguments(values), data, jsonPath); + } + + static List unpackArguments(List values) { if (values.size() == 1 && ArrayLike.isEligible(values.get(0))) { - values = new ArrayLike(values.get(0)); + return new ArrayLike(values.get(0)); } - - return evaluate(values, data, jsonPath); + return values; } } diff --git a/src/test/java/io/github/jamsesso/jsonlogic/InExpressionTests.java b/src/test/java/io/github/jamsesso/jsonlogic/InExpressionTests.java index 8d5107b..ccc8698 100644 --- a/src/test/java/io/github/jamsesso/jsonlogic/InExpressionTests.java +++ b/src/test/java/io/github/jamsesso/jsonlogic/InExpressionTests.java @@ -1,18 +1,86 @@ package io.github.jamsesso.jsonlogic; +import io.github.jamsesso.jsonlogic.ast.*; +import io.github.jamsesso.jsonlogic.evaluator.JsonLogicEvaluator; +import io.github.jamsesso.jsonlogic.evaluator.expressions.InExpression; import org.junit.Test; +import java.util.AbstractList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Locale; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; public class InExpressionTests { private static final JsonLogic jsonLogic = new JsonLogic(); + private static final String CODES = "[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\"," + + "\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"1\",\"A\"]"; + private static final String CODE_RULE = "{\"in\":[{\"var\":\"code\"}," + CODES + "]}"; + + @Test + public void indexedLookupPreservesLocalizedArgumentPath() throws JsonLogicException { + Locale previous = Locale.getDefault(Locale.Category.FORMAT); + try { + Locale.setDefault(Locale.Category.FORMAT, Locale.forLanguageTag("ar-EG")); + String expected = String.format("$.in[%d]", 0); + try { + jsonLogic.apply("{\"in\":[{\"undefined\":[]}," + CODES + "]}", null); + fail("Expected an undefined operation error"); + } catch (JsonLogicException e) { + assertEquals(expected, e.getJsonPath()); + } + } finally { + Locale.setDefault(Locale.Category.FORMAT, previous); + } + } + + @Test + public void fixedStringListMatchesEachInputWithoutCoercion() throws JsonLogicException { + assertEquals(true, jsonLogic.apply(CODE_RULE, Collections.singletonMap("code", "N"))); + assertEquals(false, jsonLogic.apply(CODE_RULE, Collections.singletonMap("code", "Z"))); + assertEquals(true, jsonLogic.apply(CODE_RULE, Collections.singletonMap("code", "1"))); + assertEquals(false, jsonLogic.apply(CODE_RULE, Collections.singletonMap("code", 1))); + assertEquals(false, jsonLogic.apply(CODE_RULE, Collections.emptyMap())); + } + + @Test + public void expressionInsideListStillUsesCurrentData() throws JsonLogicException { + String rule = CODE_RULE.replace("\"N\"", "{\"var\":\"allowed\"}"); + assertEquals(true, jsonLogic.apply(rule, Collections.singletonMap("code", "A"))); + assertEquals(false, jsonLogic.apply(rule, Collections.singletonMap("code", "N"))); + Map data = new HashMap<>(); + data.put("code", "N"); + data.put("allowed", "N"); + assertEquals(true, jsonLogic.apply(rule, data)); + } + + @Test + public void overriddenInReceivesOriginalStringsInOrder() throws JsonLogicException { + JsonLogic logic = new JsonLogic(); + assertEquals(true, logic.apply(CODE_RULE, Collections.singletonMap("code", "N"))); + logic.addOperation("in", args -> args[1]); + assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", + "I", "J", "K", "L", "M", "N", "1", "A"), logic.apply(CODE_RULE, null)); + } + + @Test + public void computedNonStringNeedleIsEvaluatedOnce() throws JsonLogicException { + AtomicInteger calls = new AtomicInteger(); + JsonLogic logic = new JsonLogic().addOperation("next", args -> calls.incrementAndGet()); + String rule = "{\"in\":[{\"next\":[]}," + CODES + "]}"; + assertEquals(false, logic.apply(rule, null)); + assertEquals(1, calls.get()); + } @Test public void testStringIn() throws JsonLogicException { @@ -44,6 +112,71 @@ public void testInVariableInt() throws JsonLogicException { assertEquals(true, jsonLogic.apply("{\"in\": [2, {\"var\": \"list\"}]}", data)); } + @Test + public void readsTheWholeInputListEvenAfterFirstMatch() throws JsonLogicException { + AtomicInteger reads = new AtomicInteger(); + List items = new AbstractList() { + @Override + public Integer get(int index) { + reads.incrementAndGet(); + return 42; + } + + @Override + public int size() { + return 2; + } + }; + assertEquals(true, jsonLogic.apply("{\"in\":[42,{\"var\":\"\"}]}", items)); + assertEquals(2, reads.get()); + } + + @Test + public void editsThroughLiteralListViewsAffectTheNextEvaluation() throws JsonLogicException { + JsonLogicOperation op = (JsonLogicOperation) JsonLogicParser.parse("{\"in\":[\"B\"," + CODES + "]}"); + JsonLogicEvaluator evaluator = new JsonLogicEvaluator(Collections.singletonList(InExpression.INSTANCE)); + JsonLogicArray literals = (JsonLogicArray) op.getArguments().get(1); + assertEquals(true, evaluator.evaluate(op, null, "$")); + + ListIterator it = literals.listIterator(1); + it.next(); + it.remove(); + assertEquals(false, evaluator.evaluate(op, null, "$")); + it.add(new JsonLogicString("B")); + assertEquals(true, evaluator.evaluate(op, null, "$")); + literals.subList(1, 2).clear(); + assertEquals(false, evaluator.evaluate(op, null, "$")); + } + + @Test + public void indexedMatchStillEvaluatesAnAppendedArgument() throws JsonLogicException { + JsonLogicOperation op = (JsonLogicOperation) JsonLogicParser.parse("{\"in\":[\"A\"," + CODES + "]}"); + JsonLogicEvaluator evaluator = new JsonLogicEvaluator(Collections.singletonList(InExpression.INSTANCE)); + JsonLogicArray args = op.getArguments(); + args.listIterator(args.size()).add(JsonLogicParser.parse("{\"undefined\":[]}")); + try { + evaluator.evaluate(op, null, "$"); + fail("Expected an undefined operation error in the appended argument"); + } catch (JsonLogicException e) { + assertEquals(String.format("$.in[%d]", 2), e.getJsonPath()); + } + } + + @Test(expected = IllegalStateException.class) + public void laterListReadCanStillFailAfterAMatch() throws JsonLogicException { + List items = new AbstractList() { + @Override + public String get(int index) { + if (index == 0) return "found"; + throw new IllegalStateException("later read failed"); + } + + @Override + public int size() { return 2; } + }; + jsonLogic.apply("{\"in\":[\"found\",{\"var\":\"\"}]}", items); + } + @Test public void testNotInVariableInt() throws JsonLogicException { Map data = Collections.singletonMap("list", Arrays.asList(1, 2, 3));