cdc.applic.expressions.ast.visitors.PredicateCounter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cdc-applic-expressions Show documentation
Show all versions of cdc-applic-expressions Show documentation
Applicabilities Expressions.
package cdc.applic.expressions.ast.visitors;
import java.util.function.Predicate;
import cdc.applic.expressions.ast.AbstractBinaryNode;
import cdc.applic.expressions.ast.AbstractLeafNode;
import cdc.applic.expressions.ast.AbstractNaryNode;
import cdc.applic.expressions.ast.AbstractUnaryNode;
import cdc.applic.expressions.ast.Node;
import cdc.util.lang.Checks;
/**
* Utility class used to count the node in an AST that match a predicate.
*
* @author Damien Carbonne
*/
public final class PredicateCounter extends AbstractAnalyzer {
public int count = 0;
private final Predicate super Node> predicate;
private PredicateCounter(Predicate super Node> predicate) {
this.predicate = predicate;
}
/**
* Returns the number of nodes that match a predicate.
*
* @param node The root node of traversal.
* @param predicate The predicate.
* @return The number of nodes in the tree rooted in {@code node} that match {@code predicate}.
*/
public static int count(Node node,
Predicate super Node> predicate) {
Checks.isNotNull(node, "node");
Checks.isNotNull(predicate, "predicate");
final PredicateCounter visitor = new PredicateCounter(predicate);
node.accept(visitor);
return visitor.count;
}
@Override
public Void visitLeaf(AbstractLeafNode node) {
if (predicate.test(node)) {
count++;
}
return null;
}
@Override
public Void visitUnary(AbstractUnaryNode node) {
if (predicate.test(node)) {
count++;
}
return super.visitUnary(node);
}
@Override
public Void visitBinary(AbstractBinaryNode node) {
if (predicate.test(node)) {
count++;
}
return super.visitBinary(node);
}
@Override
public Void visitNary(AbstractNaryNode node) {
if (predicate.test(node)) {
count++;
}
return super.visitNary(node);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy