All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.applic.expressions.ast.visitors.PredicateCounter Maven / Gradle / Ivy

There is a newer version: 0.13.3
Show newest version
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 predicate;

    private PredicateCounter(Predicate 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 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