Fix descendantOrSelf on leaf

With a leaf node it used to return empty
This commit is contained in:
Clément Fournier
2020-08-07 02:58:27 +02:00
parent feefc08c56
commit ab0aaadd64
3 changed files with 11 additions and 3 deletions

View File

@ -19,6 +19,7 @@ import net.sourceforge.pmd.internal.util.AssertionUtil;
import net.sourceforge.pmd.internal.util.IteratorUtil;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.NodeStream.DescendantNodeStream;
/**
* Optimised node stream implementation for a single element. Streams
@ -32,11 +33,12 @@ import net.sourceforge.pmd.lang.ast.NodeStream;
* <p>This ensures that short pipelines like {@code node.descendants().first()}
* are as efficient as the pre 7.0.0 methods.
*/
final class SingletonNodeStream<T extends Node> extends IteratorBasedNStream<T> {
final class SingletonNodeStream<T extends Node> extends IteratorBasedNStream<T> implements DescendantNodeStream<T> {
private final T node;
SingletonNodeStream(@NonNull T node) {
assert node != null : "null node!";
this.node = node;
}
@ -207,4 +209,9 @@ final class SingletonNodeStream<T extends Node> extends IteratorBasedNStream<T>
public NodeStream<Node> precedingSiblings() {
return StreamImpl.precedingSiblings(node);
}
@Override
public DescendantNodeStream<T> crossFindBoundaries(boolean cross) {
return this; // doesn't mean anything
}
}

View File

@ -38,7 +38,7 @@ public final class StreamImpl {
// utility class
}
public static <T extends Node> NodeStream<T> singleton(@NonNull T node) {
public static <T extends Node> DescendantNodeStream<T> singleton(@NonNull T node) {
return new SingletonNodeStream<>(node);
}
@ -88,7 +88,7 @@ public final class StreamImpl {
}
public static DescendantNodeStream<Node> descendantsOrSelf(@NonNull Node node) {
return node.getNumChildren() == 0 ? empty() : new DescendantOrSelfStream(node, TreeWalker.DEFAULT);
return node.getNumChildren() == 0 ? singleton(node) : new DescendantOrSelfStream(node, TreeWalker.DEFAULT);
}
public static NodeStream<Node> followingSiblings(@NonNull Node node) {

View File

@ -124,6 +124,7 @@ public class NodeStreamTest {
public void testDescendantOrSelfStream() {
assertThat(pathsOf(tree1.descendantsOrSelf()), contains("", "0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(NodeStream.of(tree1).descendantsOrSelf()), contains("", "0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(followPath(tree1, "0110").descendantsOrSelf()), contains("0110")); // with a leaf node
}
@Test