From b84afad4ad7b7445f8a35ec96cfd90c2b03eb791 Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Sat, 21 Nov 2026 21:25:20 +0100 Subject: [PATCH 1/4] feat(uiautomator2-server): add a class chain query parser Parses `**/Type[`pred`][$descendant pred$][n]/Type...` into an immutable ClassChain of ChainSteps, reusing PredicateParser for the predicates. Parser and AST only, nothing uses it yet. Co-Authored-By: Claude Sonnet 5.5 --- .../exceptions/ClassChainSyntaxException.java | 47 +++ .../utils/classchain/ChainStep.java | 121 +++++++ .../utils/classchain/ClassChain.java | 54 +++ .../utils/classchain/ClassChainParser.java | 218 ++++++++++++ .../classchain/ClassChainParserTests.java | 309 ++++++++++++++++++ 5 files changed, 749 insertions(+) create mode 100644 packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java create mode 100644 packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java create mode 100644 packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java create mode 100644 packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java create mode 100644 packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java new file mode 100644 index 0000000..8cf6f13 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.appium.uiautomator2.common.exceptions; + +/** + * Thrown when a class chain query cannot be parsed. The position is a 0-based character offset. + */ +public class ClassChainSyntaxException extends InvalidSelectorException { + private final String query; + private final String reason; + private final int position; + + public ClassChainSyntaxException(String query, String reason, int position) { + super(String.format("Cannot parse class chain query '%s'. %s at position %d", + query, reason, position)); + this.query = query; + this.reason = reason; + this.position = position; + } + + public String getQuery() { + return query; + } + + public String getReason() { + return reason; + } + + public int getPosition() { + return position; + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java new file mode 100644 index 0000000..8826642 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java @@ -0,0 +1,121 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.appium.uiautomator2.utils.classchain; + +import androidx.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import io.appium.uiautomator2.utils.predicate.PredicateNode; + +/** + * One immutable step of a class chain, e.g. {@code android.widget.TextView[`text == 'A'`][2]}. + */ +public final class ChainStep { + + /** {@code SELF} filters the candidates, {@code DESCENDANT} keeps those having a matching descendant */ + public enum Scope { + SELF('`'), DESCENDANT('$'); + + private final char marker; + + Scope(char marker) { + this.marker = marker; + } + + public char getMarker() { + return marker; + } + } + + public static final class Filter { + private final Scope scope; + private final PredicateNode predicate; + + Filter(Scope scope, PredicateNode predicate) { + this.scope = scope; + this.predicate = predicate; + } + + public Scope getScope() { + return scope; + } + + public PredicateNode getPredicate() { + return predicate; + } + + @Override + public String toString() { + String marker = String.valueOf(scope.getMarker()); + return "[" + marker + predicate.toString().replace(marker, marker + marker) + marker + "]"; + } + } + + private final boolean descendant; + @Nullable + private final String className; + private final List filters; + @Nullable + private final Integer position; + + ChainStep(boolean descendant, @Nullable String className, List filters, + @Nullable Integer position) { + this.descendant = descendant; + this.className = className; + this.filters = Collections.unmodifiableList(new ArrayList<>(filters)); + this.position = position; + } + + /** True for any depth below the previous step (or the root), false for direct children */ + public boolean isDescendant() { + return descendant; + } + + /** The exact class name, or null for {@code *} */ + @Nullable + public String getClassName() { + return className; + } + + /** In source order */ + public List getFilters() { + return filters; + } + + /** 1-based among the matches of the class name and filters; negative counts from the end; never 0 */ + @Nullable + public Integer getPosition() { + return position; + } + + /** The step without its axis ({@code **}{@code /}), which {@link ClassChain} adds */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(className == null ? "*" : className); + for (Filter filter : filters) { + sb.append(filter); + } + if (position != null) { + sb.append('[').append(position).append(']'); + } + return sb.toString(); + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java new file mode 100644 index 0000000..0191279 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.appium.uiautomator2.utils.classchain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * A parsed class chain: at least one step. The first step is relative to the search root + * (window roots or the context element). + */ +public final class ClassChain { + private final List steps; + + ClassChain(List steps) { + this.steps = Collections.unmodifiableList(new ArrayList<>(steps)); + } + + public List getSteps() { + return steps; + } + + /** Canonical form, which parses back to an equal chain */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < steps.size(); i++) { + ChainStep step = steps.get(i); + if (i == 0) { + sb.append(step.isDescendant() ? "**/" : ""); + } else { + sb.append(step.isDescendant() ? "/**/" : "/"); + } + sb.append(step); + } + return sb.toString(); + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java new file mode 100644 index 0000000..c6bb8d7 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java @@ -0,0 +1,218 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.appium.uiautomator2.utils.classchain; + +import androidx.annotation.Nullable; + +import java.util.ArrayList; +import java.util.List; + +import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; +import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Filter; +import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; +import io.appium.uiautomator2.utils.predicate.PredicateParser; + +/** + * Hand-written parser of class chain queries, modelled on WebDriverAgent's: + *
+ * chain  := ["**/"] step ( "/" | "/**/" ) step )*
+ * step   := ("*" | className) filter* [position]
+ * filter := "[`" predicate "`]" | "[$" predicate "$]"
+ * 
+ * Whitespace is only allowed inside predicates, and a doubled {@code `} or {@code $} inside a + * predicate stands for the character itself. See {@link PredicateParser} for the predicates. + */ +public final class ClassChainParser { + private static final String DESCENDANT_MARKER = "**/"; + + private final String source; + private int pos; + + private ClassChainParser(String source) { + this.source = source; + } + + public static ClassChain parse(String query) { + if (query == null || query.isEmpty()) { + throw new ClassChainSyntaxException(String.valueOf(query), + "The class chain must not be empty", 0); + } + return new ClassChainParser(query).parseChain(); + } + + private ClassChain parseChain() { + List steps = new ArrayList<>(); + boolean descendant = source.startsWith(DESCENDANT_MARKER); + if (descendant) { + pos = DESCENDANT_MARKER.length(); + } + while (true) { + steps.add(parseStep(descendant)); + if (pos >= source.length()) { + return new ClassChain(steps); + } + pos++; // the '/' that parseStep stopped at + descendant = source.startsWith(DESCENDANT_MARKER, pos); + if (descendant) { + pos += DESCENDANT_MARKER.length(); + } + } + } + + private ChainStep parseStep(boolean descendant) { + String className = parseType(); + List filters = new ArrayList<>(); + Integer position = null; + while (peek() == '[') { + char next = peek(1); + if (next == '`' || next == '$') { + if (position != null) { + throw error("Predicates must be set before the position"); + } + filters.add(parseFilter(next == '`' ? Scope.SELF : Scope.DESCENDANT)); + } else { + if (position != null) { + throw error("The position can be set only once"); + } + position = parsePosition(); + } + } + if (pos < source.length() && peek() != '/') { + throw error(String.format("Unexpected '%s'", peek())); + } + return new ChainStep(descendant, className, filters, position); + } + + @Nullable + private String parseType() { + if (peek() == '*') { + if (peek(1) == '*') { + throw error("Unexpected '**', the descendant marker '**/' must be followed by " + + "a class name or '*'"); + } + pos++; + return null; + } + int start = pos; + while (true) { + if (!isIdentifierStart(peek())) { + throw error(pos >= source.length() && pos > start + ? "The class name must not end with '.'" + : "Expected a class name or '*'"); + } + while (isIdentifierPart(peek())) { + pos++; + } + if (peek() != '.') { + return source.substring(start, pos); + } + pos++; + } + } + + private Filter parseFilter(Scope scope) { + char marker = scope.getMarker(); + int open = pos; + pos += 2; // "[" and the marker + int contentStart = pos; + StringBuilder text = new StringBuilder(); + while (true) { + if (pos >= source.length()) { + throw error(String.format("Cannot find the closing '%s' of the predicate", marker), + open); + } + char c = source.charAt(pos); + if (c == marker) { + if (peek(1) == marker) { + text.append(c); + pos += 2; + continue; + } + pos++; + break; + } + text.append(c); + pos++; + } + if (peek() != ']') { + throw error("Expected ']' after the predicate"); + } + pos++; + try { + return new Filter(scope, PredicateParser.parse(text.toString())); + } catch (PredicateSyntaxException e) { + throw error(String.format("Invalid predicate: %s (offset %d inside the predicate)", + e.getReason(), e.getPosition()), contentStart); + } + } + + private int parsePosition() { + pos++; // '[' + int start = pos; + if (peek() == '-') { + pos++; + } + int digitsStart = pos; + while (peek() >= '0' && peek() <= '9') { + pos++; + } + if (pos == digitsStart) { + throw error("Expected a predicate or an integer position after '['", start); + } + int value; + try { + value = Integer.parseInt(source.substring(start, pos)); + } catch (NumberFormatException e) { + throw error("The position is out of the integer range", start); + } + if (value == 0) { + throw error("The position must be a non-zero integer, counted from 1", start); + } + if (peek() != ']') { + throw error("Expected ']' after the position"); + } + pos++; + return value; + } + + private static boolean isIdentifierStart(char c) { + return c != '\0' && Character.isJavaIdentifierStart(c) && !Character.isIdentifierIgnorable(c); + } + + private static boolean isIdentifierPart(char c) { + return c != '\0' && Character.isJavaIdentifierPart(c) && !Character.isIdentifierIgnorable(c); + } + + private char peek() { + return peek(0); + } + + private char peek(int offset) { + int index = pos + offset; + return index < source.length() ? source.charAt(index) : '\0'; + } + + private ClassChainSyntaxException error(String reason) { + return error(reason, pos); + } + + private ClassChainSyntaxException error(String reason, int position) { + return new ClassChainSyntaxException(source, reason, position); + } +} diff --git a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java new file mode 100644 index 0000000..603998d --- /dev/null +++ b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java @@ -0,0 +1,309 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.appium.uiautomator2.utils.classchain; + +import org.junit.Test; + +import java.util.List; + +import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; +import io.appium.uiautomator2.common.exceptions.InvalidSelectorException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class ClassChainParserTests { + private static final String BUTTON = "android.widget.Button"; + private static final String VIEW = "android.view.View"; + + private static List steps(String query) { + return ClassChainParser.parse(query).getSteps(); + } + + private static String canonical(String query) { + return ClassChainParser.parse(query).toString(); + } + + private static ClassChainSyntaxException assertInvalid(String query, String reasonPart) { + try { + ClassChainParser.parse(query); + } catch (ClassChainSyntaxException e) { + assertTrue(String.format("'%s' not in '%s'", reasonPart, e.getReason()), + e.getReason().contains(reasonPart)); + return e; + } + fail("Expected a syntax error for: " + query); + return null; + } + + private static void assertStep(ChainStep step, boolean descendant, String className, + Integer position, int filters) { + assertEquals(descendant, step.isDescendant()); + assertEquals(className, step.getClassName()); + assertEquals(position, step.getPosition()); + assertEquals(filters, step.getFilters().size()); + } + + // ---- valid chains (ported from WDA's FBClassChainTests) ---- + + @Test + public void childChain() { + List steps = steps(VIEW + "/" + BUTTON); + assertEquals(2, steps.size()); + assertStep(steps.get(0), false, VIEW, null, 0); + assertStep(steps.get(1), false, BUTTON, null, 0); + } + + @Test + public void starsAndPositions() { + List steps = steps(VIEW + "/" + BUTTON + "[3]/*[4]/*[5]/android.app.Dialog"); + assertEquals(5, steps.size()); + assertStep(steps.get(1), false, BUTTON, 3, 0); + assertStep(steps.get(2), false, null, 4, 0); + assertStep(steps.get(3), false, null, 5, 0); + assertStep(steps.get(4), false, "android.app.Dialog", null, 0); + } + + @Test + public void singleStar() { + List steps = steps("*"); + assertEquals(1, steps.size()); + assertStep(steps.get(0), false, null, null, 0); + } + + @Test + public void leadingDescendantMarker() { + List steps = steps("**/*/*/" + BUTTON); + assertEquals(3, steps.size()); + assertStep(steps.get(0), true, null, null, 0); + assertStep(steps.get(1), false, null, null, 0); + assertStep(steps.get(2), false, BUTTON, null, 0); + } + + @Test + public void descendantMarkersInTheMiddle() { + List steps = steps("**/" + BUTTON + "/**/*"); + assertEquals(2, steps.size()); + assertStep(steps.get(0), true, BUTTON, null, 0); + assertStep(steps.get(1), true, null, null, 0); + steps = steps(VIEW + "/**/" + BUTTON + "/" + VIEW); + assertStep(steps.get(0), false, VIEW, null, 0); + assertStep(steps.get(1), true, BUTTON, null, 0); + assertStep(steps.get(2), false, VIEW, null, 0); + } + + @Test + public void negativePosition() { + List steps = steps(VIEW + "/" + BUTTON + "[-1]"); + assertStep(steps.get(1), false, BUTTON, -1, 0); + } + + @Test + public void predicates() { + List steps = steps(VIEW + "[`text == 'a'`]/" + BUTTON + "[`checked == true`]"); + assertStep(steps.get(0), false, VIEW, null, 1); + assertStep(steps.get(1), false, BUTTON, null, 1); + assertEquals(Scope.SELF, steps.get(0).getFilters().get(0).getScope()); + assertEquals("text == 'a'", steps.get(0).getFilters().get(0).getPredicate().toString()); + } + + @Test + public void descendantAndSelfPredicatesKeepTheirOrder() { + List steps = steps("**/" + VIEW + "[$text == 'a' AND enabled == true$]" + + "[`checked == true`][$clickable == true$][`text == 'b'`][10]"); + assertEquals(1, steps.size()); + ChainStep step = steps.get(0); + assertStep(step, true, VIEW, 10, 4); + assertEquals(Scope.DESCENDANT, step.getFilters().get(0).getScope()); + assertEquals(Scope.SELF, step.getFilters().get(1).getScope()); + assertEquals(Scope.DESCENDANT, step.getFilters().get(2).getScope()); + assertEquals(Scope.SELF, step.getFilters().get(3).getScope()); + } + + @Test + public void predicateEscapes() { + ChainStep step = steps("*[`text == \"к``ири````'лиця\"`][3]").get(0); + assertEquals("text == 'к`ири``\\'лиця'", + step.getFilters().get(0).getPredicate().toString()); + assertEquals(Integer.valueOf(3), step.getPosition()); + ChainStep dollar = steps("*[$text == 'a$$b'$]").get(0); + assertEquals("text == 'a$b'", dollar.getFilters().get(0).getPredicate().toString()); + } + + @Test + public void brackets() { + // brackets and the other marker are plain characters inside a predicate + ChainStep step = steps("*[`text == '[1]$'`][`text == 'a``]``'`][2]").get(0); + assertEquals(2, step.getFilters().size()); + } + + // ---- class names ---- + + @Test + public void classNames() { + assertEquals("android.widget.TextView", steps("android.widget.TextView").get(0).getClassName()); + assertEquals("Button", steps("Button").get(0).getClassName()); + assertEquals("androidx.recyclerview.widget.RecyclerView$ViewHolder", + steps("androidx.recyclerview.widget.RecyclerView$ViewHolder").get(0).getClassName()); + assertEquals("a.b$1", steps("a.b$1").get(0).getClassName()); + assertEquals("com.example.Вид", steps("com.example.Вид").get(0).getClassName()); + } + + @Test + public void dollarInClassNameIsNotAPredicateMarker() { + ChainStep step = steps("a.B$C[$text == 'x'$]").get(0); + assertEquals("a.B$C", step.getClassName()); + assertEquals(Scope.DESCENDANT, step.getFilters().get(0).getScope()); + } + + // ---- canonical form ---- + + @Test + public void canonicalFormRoundTrips() { + String[] queries = { + "*", "**/*", VIEW + "/" + BUTTON + "[2]", "**/" + VIEW + "/**/" + BUTTON + "[-1]", + "**/" + VIEW + "[`text == 'a``b' AND checked == true`][$enabled == true$][3]", + "*[`text == 'a$b'`][$text == 'a$$b'$]", + }; + for (String query : queries) { + String canonical = canonical(query); + assertEquals(canonical, canonical(canonical)); + } + assertEquals("**/*[`text == 'a``b'`]", canonical("**/*[`text == 'a``b'`]")); + assertEquals("*[$text == 'a$$b'$]", canonical("*[$text=='a$$b'$]")); + } + + // ---- invalid chains (ported from WDA's testInvalidChains) ---- + + @Test + public void invalidStructure() { + String[] queries = { + "/" + VIEW, VIEW + "/", VIEW + "//*", VIEW + "*/*", "**", "***", "**/*/**", "/**", + VIEW + "/**", "**[1]/" + VIEW, "**[`text == '1'`]/" + VIEW, "**/**/*", "**/", + "*/", " " + VIEW, VIEW + " ", VIEW + "/ " + BUTTON, "a..b", "a.", ".a", "1a", "a-b", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void invalidPositions() { + String[] queries = { + VIEW + "[0]", VIEW + "[-0]", VIEW + "[1][1]", VIEW + "[ 2 ]", VIEW + "[[2]", + VIEW + "[2]]", VIEW + "[]", VIEW + "[-]", VIEW + "[+1]", VIEW + "[1.5]", + VIEW + "[99999999999]", VIEW + "[1", VIEW + "[0x1]", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void invalidPredicates() { + String[] queries = { + VIEW + "[text = 'a']", VIEW + "[1][`checked == true`]", + VIEW + "[1] [`checked == true`]", VIEW + "[ `checked == true`]", + VIEW + "[`checked == true][`text == 'a'`]", VIEW + "[`checked == true]", + VIEW + "[$checked == true]", VIEW + "[``]", VIEW + "[$$]", + VIEW + "[`text == \"bla```bla\"`]", VIEW + "[$text == \"bla$$$bla\"$]", + VIEW + "[`checked == true` ]", VIEW + "[`checked == true`x]", + VIEW + "[`unknown == 1`]", VIEW + "[`text ==`]", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void emptyQuery() { + assertInvalid("", "must not be empty"); + try { + ClassChainParser.parse(null); + fail(); + } catch (ClassChainSyntaxException e) { + assertTrue(e.getReason().contains("must not be empty")); + } + } + + // ---- error reporting ---- + + @Test + public void errorsAreInvalidSelectorExceptionsWithPositions() { + ClassChainSyntaxException e = assertInvalid(VIEW + "[0]", "non-zero"); + assertTrue(e instanceof InvalidSelectorException); + assertEquals(VIEW.length() + 1, e.getPosition()); + assertEquals(VIEW + "[0]", e.getQuery()); + assertEquals(String.format("Cannot parse class chain query '%s[0]'. %s at position %d", + VIEW, e.getReason(), e.getPosition()), e.getMessage()); + + assertEquals(1, assertInvalid("a/", "Expected a class name").getPosition() - 1); + assertEquals(2, assertInvalid("a/", "Expected a class name").getPosition()); + assertEquals(1, assertInvalid("a/**", "descendant marker").getPosition() - 1); + assertEquals(0, assertInvalid("**", "descendant marker").getPosition()); + assertEquals(1, assertInvalid("a ", "Unexpected ' '").getPosition()); + assertEquals(3, assertInvalid("a.b.", "must not end with '.'").getPosition() - 1); + assertEquals(1, assertInvalid("a[1][2]", "only once").getPosition() - 3); + assertEquals(4, assertInvalid("a[1][`x == 1`]", "before the position").getPosition()); + } + + @Test + public void unterminatedPredicateReportsTheOpeningBracket() { + ClassChainSyntaxException e = assertInvalid("a/b[`text == 'x'", "closing '`'"); + assertEquals(3, e.getPosition()); + e = assertInvalid("a[$text == 'x'", "closing '$'"); + assertEquals(1, e.getPosition()); + } + + @Test + public void predicateErrorsPointAtThePredicateAndKeepTheReason() { + ClassChainSyntaxException e = assertInvalid("a[`bogus == 1`]", "Invalid predicate"); + assertTrue(e.getReason(), e.getReason().contains("bogus")); + assertEquals(3, e.getPosition()); + e = assertInvalid("a[``]", "must not be empty"); + assertEquals(3, e.getPosition()); + } + + @Test + public void nonDecimalLiteralsAreRejectedInsideChains() { + assertInvalid("*[`inputType == 0x1`]", "not supported"); + } + + @Test + public void stepsAreImmutable() { + List steps = steps("a/b"); + try { + steps.add(steps.get(0)); + fail(); + } catch (UnsupportedOperationException expected) { + // expected + } + assertFalse(steps.get(0).isDescendant()); + assertNull(steps.get(0).getPosition()); + try { + steps.get(0).getFilters().add(null); + fail(); + } catch (UnsupportedOperationException expected) { + // expected + } + } +} From 47a76a7561537592f4f91556b49bed13488cf9df Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Sat, 21 Nov 2026 21:29:06 +0100 Subject: [PATCH 2/4] fix(uiautomator2-server): report exact predicate error positions in class chains Map predicate error offsets back to the query when doubled markers were collapsed, chain the predicate exception as the cause, accept supplementary-plane identifier characters in class names, and tidy the Javadoc and line lengths. Co-Authored-By: Claude Sonnet 5.5 --- .../exceptions/ClassChainSyntaxException.java | 9 +++- .../utils/classchain/ChainStep.java | 7 +-- .../utils/classchain/ClassChain.java | 2 +- .../utils/classchain/ClassChainParser.java | 45 ++++++++++--------- .../classchain/ClassChainParserTests.java | 26 ++++++++++- 5 files changed, 61 insertions(+), 28 deletions(-) diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java index 8cf6f13..324509a 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java @@ -17,6 +17,8 @@ package io.appium.uiautomator2.common.exceptions; +import androidx.annotation.Nullable; + /** * Thrown when a class chain query cannot be parsed. The position is a 0-based character offset. */ @@ -26,8 +28,13 @@ public class ClassChainSyntaxException extends InvalidSelectorException { private final int position; public ClassChainSyntaxException(String query, String reason, int position) { + this(query, reason, position, null); + } + + public ClassChainSyntaxException(String query, String reason, int position, + @Nullable Throwable cause) { super(String.format("Cannot parse class chain query '%s'. %s at position %d", - query, reason, position)); + query, reason, position), cause); this.query = query; this.reason = reason; this.position = position; diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java index 8826642..de032a0 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java @@ -30,7 +30,7 @@ */ public final class ChainStep { - /** {@code SELF} filters the candidates, {@code DESCENDANT} keeps those having a matching descendant */ + /** {@code SELF} filters the candidates, {@code DESCENDANT} needs a matching descendant */ public enum Scope { SELF('`'), DESCENDANT('$'); @@ -65,7 +65,8 @@ public PredicateNode getPredicate() { @Override public String toString() { String marker = String.valueOf(scope.getMarker()); - return "[" + marker + predicate.toString().replace(marker, marker + marker) + marker + "]"; + String escaped = predicate.toString().replace(marker, marker + marker); + return "[" + marker + escaped + marker + "]"; } } @@ -100,7 +101,7 @@ public List getFilters() { return filters; } - /** 1-based among the matches of the class name and filters; negative counts from the end; never 0 */ + /** 1-based among the matches of class name and filters; negative counts from the end */ @Nullable public Integer getPosition() { return position; diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java index 0191279..5445574 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java @@ -36,7 +36,7 @@ public List getSteps() { return steps; } - /** Canonical form, which parses back to an equal chain */ + /** Canonical form, which parses back to the same canonical form */ @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java index c6bb8d7..d16bf89 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java @@ -28,16 +28,7 @@ import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; import io.appium.uiautomator2.utils.predicate.PredicateParser; -/** - * Hand-written parser of class chain queries, modelled on WebDriverAgent's: - *
- * chain  := ["**/"] step ( "/" | "/**/" ) step )*
- * step   := ("*" | className) filter* [position]
- * filter := "[`" predicate "`]" | "[$" predicate "$]"
- * 
- * Whitespace is only allowed inside predicates, and a doubled {@code `} or {@code $} inside a - * predicate stands for the character itself. See {@link PredicateParser} for the predicates. - */ +/** Parser of class chain queries like WebDriverAgent's, with {@link PredicateParser} predicates. */ public final class ClassChainParser { private static final String DESCENDANT_MARKER = "**/"; @@ -111,14 +102,14 @@ private String parseType() { } int start = pos; while (true) { - if (!isIdentifierStart(peek())) { + if (!isIdentifierStart(codePoint())) { throw error(pos >= source.length() && pos > start ? "The class name must not end with '.'" : "Expected a class name or '*'"); } - while (isIdentifierPart(peek())) { - pos++; - } + do { + pos += Character.charCount(codePoint()); + } while (isIdentifierPart(codePoint())); if (peek() != '.') { return source.substring(start, pos); } @@ -130,8 +121,9 @@ private Filter parseFilter(Scope scope) { char marker = scope.getMarker(); int open = pos; pos += 2; // "[" and the marker - int contentStart = pos; StringBuilder text = new StringBuilder(); + // source index of each predicate character, so errors point into the query + int[] sourceIndex = new int[source.length() + 1]; while (true) { if (pos >= source.length()) { throw error(String.format("Cannot find the closing '%s' of the predicate", marker), @@ -140,13 +132,16 @@ private Filter parseFilter(Scope scope) { char c = source.charAt(pos); if (c == marker) { if (peek(1) == marker) { + sourceIndex[text.length()] = pos; text.append(c); pos += 2; continue; } + sourceIndex[text.length()] = pos; pos++; break; } + sourceIndex[text.length()] = pos; text.append(c); pos++; } @@ -157,8 +152,9 @@ private Filter parseFilter(Scope scope) { try { return new Filter(scope, PredicateParser.parse(text.toString())); } catch (PredicateSyntaxException e) { - throw error(String.format("Invalid predicate: %s (offset %d inside the predicate)", - e.getReason(), e.getPosition()), contentStart); + int at = sourceIndex[Math.min(e.getPosition(), text.length())]; + throw new ClassChainSyntaxException( + source, "Invalid predicate: " + e.getReason(), at, e); } } @@ -191,12 +187,19 @@ private int parsePosition() { return value; } - private static boolean isIdentifierStart(char c) { - return c != '\0' && Character.isJavaIdentifierStart(c) && !Character.isIdentifierIgnorable(c); + /** The code point at the current position, or -1 at the end */ + private int codePoint() { + return pos < source.length() ? source.codePointAt(pos) : -1; + } + + private static boolean isIdentifierStart(int cp) { + return cp > 0 && Character.isJavaIdentifierStart(cp) + && !Character.isIdentifierIgnorable(cp); } - private static boolean isIdentifierPart(char c) { - return c != '\0' && Character.isJavaIdentifierPart(c) && !Character.isIdentifierIgnorable(c); + private static boolean isIdentifierPart(int cp) { + return cp > 0 && Character.isJavaIdentifierPart(cp) + && !Character.isIdentifierIgnorable(cp); } private char peek() { diff --git a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java index 603998d..1bbe704 100644 --- a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java +++ b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java @@ -23,6 +23,7 @@ import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; import io.appium.uiautomator2.common.exceptions.InvalidSelectorException; +import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; import static org.junit.Assert.assertEquals; @@ -158,12 +159,21 @@ public void brackets() { // ---- class names ---- + @Test + public void supplementaryPlaneIdentifiers() { + String name = "com.example.\uD835\uDC00View"; // MATHEMATICAL BOLD CAPITAL A + assertEquals(name, steps(name + "/*").get(0).getClassName()); + assertEquals(name.length() + 1, assertInvalid(name + "/ ", "Expected").getPosition()); + } + @Test public void classNames() { - assertEquals("android.widget.TextView", steps("android.widget.TextView").get(0).getClassName()); + assertEquals("android.widget.TextView", + steps("android.widget.TextView").get(0).getClassName()); assertEquals("Button", steps("Button").get(0).getClassName()); assertEquals("androidx.recyclerview.widget.RecyclerView$ViewHolder", - steps("androidx.recyclerview.widget.RecyclerView$ViewHolder").get(0).getClassName()); + steps("androidx.recyclerview.widget.RecyclerView$ViewHolder") + .get(0).getClassName()); assertEquals("a.b$1", steps("a.b$1").get(0).getClassName()); assertEquals("com.example.Вид", steps("com.example.Вид").get(0).getClassName()); } @@ -279,10 +289,22 @@ public void predicateErrorsPointAtThePredicateAndKeepTheReason() { ClassChainSyntaxException e = assertInvalid("a[`bogus == 1`]", "Invalid predicate"); assertTrue(e.getReason(), e.getReason().contains("bogus")); assertEquals(3, e.getPosition()); + assertTrue(e.getCause() instanceof PredicateSyntaxException); e = assertInvalid("a[``]", "must not be empty"); assertEquals(3, e.getPosition()); } + @Test + public void predicateErrorPositionsAccountForEscapedMarkers() { + String query = "*[`text == 'a``b' AND bogus == 1`]"; + assertEquals(query.indexOf("bogus"), assertInvalid(query, "bogus").getPosition()); + query = "*[$text == 'a$$b$$c' AND bogus == 1$]"; + assertEquals(query.indexOf("bogus"), assertInvalid(query, "bogus").getPosition()); + // an error at the end of the predicate points at its closing marker + query = "*[`text == 'a``b' AND`]"; + assertEquals(query.indexOf("`]"), assertInvalid(query, "").getPosition()); + } + @Test public void nonDecimalLiteralsAreRejectedInsideChains() { assertInvalid("*[`inputType == 0x1`]", "not supported"); From 9fa313ebf543bc9a94669cd0aad619fa8ed280e8 Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Sat, 21 Nov 2026 21:38:35 +0100 Subject: [PATCH 3/4] feat(uiautomator2-server): add parent, ancestor and sibling axes to class chains `..` selects the parent, `^T` ancestors, `>T`/` --- .../utils/classchain/ChainStep.java | 43 ++++++++-- .../utils/classchain/ClassChainParser.java | 59 +++++++++++-- .../classchain/ClassChainParserTests.java | 85 +++++++++++++++++++ 3 files changed, 174 insertions(+), 13 deletions(-) diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java index de032a0..46b0531 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java @@ -70,27 +70,51 @@ public String toString() { } } - private final boolean descendant; + /** + * Where a step looks, relative to each node of the previous step (or the search root). + * Positions count along the axis: nearest first for {@code PARENT}, {@code ANCESTOR} and + * {@code PRECEDING_SIBLING}, in document order otherwise. + */ + public enum Axis { + CHILD(""), DESCENDANT(""), PARENT(".."), ANCESTOR("^"), + FOLLOWING_SIBLING(">"), PRECEDING_SIBLING("<"), SIBLING("~"); + + private final String symbol; + + Axis(String symbol) { + this.symbol = symbol; + } + + /** The prefix of the step, empty for {@code CHILD} and {@code DESCENDANT} */ + public String getSymbol() { + return symbol; + } + } + + private final Axis axis; @Nullable private final String className; private final List filters; @Nullable private final Integer position; - ChainStep(boolean descendant, @Nullable String className, List filters, + ChainStep(Axis axis, @Nullable String className, List filters, @Nullable Integer position) { - this.descendant = descendant; + this.axis = axis; this.className = className; this.filters = Collections.unmodifiableList(new ArrayList<>(filters)); this.position = position; } - /** True for any depth below the previous step (or the root), false for direct children */ + public Axis getAxis() { + return axis; + } + public boolean isDescendant() { - return descendant; + return axis == Axis.DESCENDANT; } - /** The exact class name, or null for {@code *} */ + /** The exact class name, or null for {@code *} and for the parent axis */ @Nullable public String getClassName() { return className; @@ -107,10 +131,13 @@ public Integer getPosition() { return position; } - /** The step without its axis ({@code **}{@code /}), which {@link ClassChain} adds */ + /** The step without the separator before it, which {@link ClassChain} adds */ @Override public String toString() { - StringBuilder sb = new StringBuilder(className == null ? "*" : className); + StringBuilder sb = new StringBuilder(axis.getSymbol()); + if (axis != Axis.PARENT) { + sb.append(className == null ? "*" : className); + } for (Filter filter : filters) { sb.append(filter); } diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java index d16bf89..21e4592 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java @@ -24,11 +24,16 @@ import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Axis; import io.appium.uiautomator2.utils.classchain.ChainStep.Filter; import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; import io.appium.uiautomator2.utils.predicate.PredicateParser; -/** Parser of class chain queries like WebDriverAgent's, with {@link PredicateParser} predicates. */ +/** + * Parser of class chain queries like WebDriverAgent's, with {@link PredicateParser} predicates. + * Beyond WDA, a step after {@code /} can start with {@code ..} (parent), {@code ^} (ancestors), + * {@code >} / {@code <} (following / preceding siblings) or {@code ~} (all siblings). + */ public final class ClassChainParser { private static final String DESCENDANT_MARKER = "**/"; @@ -54,7 +59,7 @@ private ClassChain parseChain() { pos = DESCENDANT_MARKER.length(); } while (true) { - steps.add(parseStep(descendant)); + steps.add(parseStep(descendant ? Axis.DESCENDANT : Axis.CHILD)); if (pos >= source.length()) { return new ClassChain(steps); } @@ -66,8 +71,9 @@ private ClassChain parseChain() { } } - private ChainStep parseStep(boolean descendant) { - String className = parseType(); + private ChainStep parseStep(Axis plainAxis) { + Axis axis = parseAxis(plainAxis); + String className = axis == Axis.PARENT ? null : parseType(); List filters = new ArrayList<>(); Integer position = null; while (peek() == '[') { @@ -81,13 +87,56 @@ private ChainStep parseStep(boolean descendant) { if (position != null) { throw error("The position can be set only once"); } + if (axis == Axis.PARENT) { + throw error("A parent step '..' has a single candidate, it takes no position"); + } position = parsePosition(); } } if (pos < source.length() && peek() != '/') { throw error(String.format("Unexpected '%s'", peek())); } - return new ChainStep(descendant, className, filters, position); + return new ChainStep(axis, className, filters, position); + } + + private Axis parseAxis(Axis plainAxis) { + Axis axis; + switch (peek()) { + case '.': + axis = Axis.PARENT; + break; + case '^': + axis = Axis.ANCESTOR; + break; + case '>': + axis = Axis.FOLLOWING_SIBLING; + break; + case '<': + axis = Axis.PRECEDING_SIBLING; + break; + case '~': + axis = Axis.SIBLING; + break; + default: + return plainAxis; + } + if (plainAxis == Axis.DESCENDANT) { + throw error(String.format("'%s' cannot follow the descendant marker '**/'", + axis.getSymbol())); + } + if (axis == Axis.PARENT) { + if (peek(1) != '.') { + throw error("Expected '..' for the parent step"); + } + pos += 2; + if (peek() == '.' || peek() == '*' || isIdentifierStart(codePoint())) { + throw error("A parent step '..' takes no class name, " + + "filter with [`className == ...`] instead"); + } + } else { + pos++; + } + return axis; } @Nullable diff --git a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java index 1bbe704..a638948 100644 --- a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java +++ b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java @@ -24,6 +24,7 @@ import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; import io.appium.uiautomator2.common.exceptions.InvalidSelectorException; import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Axis; import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; import static org.junit.Assert.assertEquals; @@ -157,6 +158,90 @@ public void brackets() { assertEquals(2, step.getFilters().size()); } + // ---- parent, ancestor and sibling axes ---- + + @Test + public void axes() { + List steps = steps(VIEW + "/../" + VIEW + "/^" + BUTTON + "/>*[2]/<" + VIEW + + "[-1]/~*"); + assertEquals(7, steps.size()); + assertEquals(Axis.CHILD, steps.get(0).getAxis()); + assertEquals(Axis.PARENT, steps.get(1).getAxis()); + assertNull(steps.get(1).getClassName()); + assertEquals(Axis.CHILD, steps.get(2).getAxis()); + assertEquals(Axis.ANCESTOR, steps.get(3).getAxis()); + assertEquals(BUTTON, steps.get(3).getClassName()); + assertEquals(Axis.FOLLOWING_SIBLING, steps.get(4).getAxis()); + assertEquals(Integer.valueOf(2), steps.get(4).getPosition()); + assertEquals(Axis.PRECEDING_SIBLING, steps.get(5).getAxis()); + assertEquals(Integer.valueOf(-1), steps.get(5).getPosition()); + assertEquals(Axis.SIBLING, steps.get(6).getAxis()); + assertNull(steps.get(6).getClassName()); + for (ChainStep step : steps) { + assertFalse(step.isDescendant()); + } + } + + @Test + public void axisAsTheFirstStepAndFollowedByDescendants() { + assertEquals(Axis.PARENT, steps("..").get(0).getAxis()); + assertEquals(Axis.PARENT, steps("../*").get(0).getAxis()); + List steps = steps(BUTTON + "/../**/" + VIEW); + assertEquals(Axis.PARENT, steps.get(1).getAxis()); + assertEquals(Axis.DESCENDANT, steps.get(2).getAxis()); + assertEquals(Axis.FOLLOWING_SIBLING, steps("**/*/>*").get(1).getAxis()); + } + + @Test + public void axisFilters() { + ChainStep parent = steps("*/..[`enabled == true`]").get(1); + assertEquals(1, parent.getFilters().size()); + ChainStep sibling = steps("*/>" + BUTTON + "[$text == 'a'$][`checked == true`][1]").get(1); + assertEquals(2, sibling.getFilters().size()); + assertEquals(Integer.valueOf(1), sibling.getPosition()); + } + + @Test + public void axesRoundTrip() { + String[] queries = { + "**/" + BUTTON + "[`text == 'OK'`]/..", "*/../*/../**/" + VIEW, + "a/^b[2]/>*[-1]/*[$text == 'x$$y'$][3]", + }; + for (String query : queries) { + assertEquals(query, canonical(query)); + } + assertEquals("a/..", canonical("a/..")); + } + + @Test + public void invalidAxes() { + assertInvalid("**/..", "cannot follow the descendant marker"); + assertInvalid("a/**/..", "cannot follow the descendant marker"); + assertInvalid("**/>a", "cannot follow the descendant marker"); + assertInvalid("a/**/^b", "cannot follow the descendant marker"); + assertInvalid("a/.", "Expected '..'"); + assertInvalid("a/...", "takes no class name"); + assertInvalid("a/..b", "takes no class name"); + assertInvalid("a/..*", "takes no class name"); + assertInvalid("a/..[1]", "takes no position"); + assertInvalid("a/>", "Expected a class name"); + assertInvalid("a/^", "Expected a class name"); + assertInvalid("a/>>b", "Expected a class name"); + assertInvalid("a/<~b", "Expected a class name"); + assertInvalid("a/>[`text == 'a'`]", "Expected a class name"); + assertInvalid("a/.. ", "Unexpected ' '"); + assertInvalid("a>b", "Unexpected '>'"); + assertInvalid("a/b^", "Unexpected '^'"); + } + + @Test + public void axisErrorPositions() { + assertEquals(2, assertInvalid("a/**/..", "cannot follow").getPosition() - 3); + assertEquals(4, assertInvalid("a/..b", "takes no class name").getPosition()); + assertEquals(4, assertInvalid("a/..[1]", "takes no position").getPosition()); + } + // ---- class names ---- @Test From d5f7440f5d13abb5a0672b99d53445d73cea79a7 Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Sun, 22 Nov 2026 08:37:26 +0100 Subject: [PATCH 4/4] fix(uiautomator2-server): avoid per-filter allocation and keep class chain round trips at the depth limit Map predicate error offsets back to the query only when the predicate fails to parse, and drop the redundant root parentheses of a logical filter in the canonical form, which added a nesting level on reparse. Co-Authored-By: Claude Sonnet 5.5 --- .../utils/classchain/ChainStep.java | 7 ++++++- .../utils/classchain/ClassChainParser.java | 19 +++++++++++++------ .../classchain/ClassChainParserTests.java | 17 +++++++++++++++++ 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java index 46b0531..eecd8b5 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java @@ -65,7 +65,12 @@ public PredicateNode getPredicate() { @Override public String toString() { String marker = String.valueOf(scope.getMarker()); - String escaped = predicate.toString().replace(marker, marker + marker); + String text = predicate.toString(); + if (predicate instanceof PredicateNode.Logical) { + // the root needs no parentheses, and they would add a nesting level on reparse + text = text.substring(1, text.length() - 1); + } + String escaped = text.replace(marker, marker + marker); return "[" + marker + escaped + marker + "]"; } } diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java index 21e4592..180f0a5 100644 --- a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java @@ -170,9 +170,8 @@ private Filter parseFilter(Scope scope) { char marker = scope.getMarker(); int open = pos; pos += 2; // "[" and the marker + int contentStart = pos; StringBuilder text = new StringBuilder(); - // source index of each predicate character, so errors point into the query - int[] sourceIndex = new int[source.length() + 1]; while (true) { if (pos >= source.length()) { throw error(String.format("Cannot find the closing '%s' of the predicate", marker), @@ -181,16 +180,13 @@ private Filter parseFilter(Scope scope) { char c = source.charAt(pos); if (c == marker) { if (peek(1) == marker) { - sourceIndex[text.length()] = pos; text.append(c); pos += 2; continue; } - sourceIndex[text.length()] = pos; pos++; break; } - sourceIndex[text.length()] = pos; text.append(c); pos++; } @@ -201,12 +197,23 @@ private Filter parseFilter(Scope scope) { try { return new Filter(scope, PredicateParser.parse(text.toString())); } catch (PredicateSyntaxException e) { - int at = sourceIndex[Math.min(e.getPosition(), text.length())]; + int at = sourceOffset(contentStart, marker, Math.min(e.getPosition(), text.length())); throw new ClassChainSyntaxException( source, "Invalid predicate: " + e.getReason(), at, e); } } + /** The query index of the {@code offset}-th predicate character, which skips doubled markers */ + private int sourceOffset(int from, char marker, int offset) { + int index = from; + for (int n = 0; n < offset && index < source.length(); n++) { + boolean doubled = source.charAt(index) == marker + && index + 1 < source.length() && source.charAt(index + 1) == marker; + index += doubled ? 2 : 1; + } + return index; + } + private int parsePosition() { pos++; // '[' int start = pos; diff --git a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java index a638948..d23e852 100644 --- a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java +++ b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java @@ -201,6 +201,23 @@ public void axisFilters() { assertEquals(Integer.valueOf(1), sibling.getPosition()); } + @Test + public void canonicalFormRoundTripsAtThePredicateDepthLimit() { + StringBuilder nots = new StringBuilder(); + for (int i = 0; i < 63; i++) { + nots.append("NOT "); + } + String query = "*[`TRUEPREDICATE AND " + nots + "TRUEPREDICATE`]"; + String canonical = canonical(query); + assertEquals(canonical, canonical(canonical)); + assertEquals("*[`TRUEPREDICATE AND " + nots + "TRUEPREDICATE`]", canonical); + // the root parentheses are only dropped at the root + assertEquals("*[`(text == 'a' OR text == 'b') AND enabled == TRUE`]", + canonical("*[`(text == 'a' OR text == 'b') AND enabled == true`]")); + assertEquals("*[`NOT (text == 'a' OR text == 'b')`]", + canonical("*[`NOT (text == 'a' OR text == 'b')`]")); + } + @Test public void axesRoundTrip() { String[] queries = {