Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions src/main/java/io/github/jamsesso/jsonlogic/ast/JsonLogicArray.java
Original file line number Diff line number Diff line change
@@ -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<JsonLogicNode> {
private final List<JsonLogicNode> delegate;
private volatile Set<String> stringIndex;

public JsonLogicArray(List<JsonLogicNode> delegate) {
this.delegate = delegate;
}

void indexStringLiterals() {
if (delegate.size() < 16) {
return;
}
Set<String> 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<String> index = stringIndex;
if (index == null || (value != null && !(value instanceof String))) {
return null;
}
return index.contains(value);
}

private List<JsonLogicNode> 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;
Expand All @@ -34,7 +68,7 @@ public boolean contains(Object o) {

@Override
public Iterator<JsonLogicNode> iterator() {
return delegate.iterator();
return mutableView().iterator();
}

@Override
Expand Down Expand Up @@ -119,16 +153,16 @@ public int lastIndexOf(Object o) {

@Override
public ListIterator<JsonLogicNode> listIterator() {
return delegate.listIterator();
return mutableView().listIterator();
}

@Override
public ListIterator<JsonLogicNode> listIterator(int index) {
return delegate.listIterator(index);
return mutableView().listIterator(index);
}

@Override
public List<JsonLogicNode> subList(int fromIndex, int toIndex) {
return delegate.subList(fromIndex, toIndex);
return mutableView().subList(fromIndex, toIndex);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<Object> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@ default Object evaluate(JsonLogicEvaluator evaluator, JsonLogicArray arguments,
throws JsonLogicEvaluationException {
List<Object> values = evaluator.evaluate(arguments, data, jsonPath);

return evaluate(unpackArguments(values), data, jsonPath);
}

static List<Object> unpackArguments(List<Object> 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;
}
}
133 changes: 133 additions & 0 deletions src/test/java/io/github/jamsesso/jsonlogic/InExpressionTests.java
Original file line number Diff line number Diff line change
@@ -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<String, String> 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 {
Expand Down Expand Up @@ -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<Integer> items = new AbstractList<Integer>() {
@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<JsonLogicNode> 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<String> items = new AbstractList<String>() {
@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));
Expand Down