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

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

The newest version!
package cdc.applic.expressions.ast.visitors;

import java.util.Collection;
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 collect nodes that match a predicate in an AST.
 *
 * @author Damien Carbonne
 */
public final class PredicateCollector extends AbstractCollector {
    private final Predicate predicate;

    private PredicateCollector(Collection collection,
                               Predicate predicate) {
        super(collection);
        this.predicate = predicate;
    }

    /**
     * Collects all the nodes that match a Predicate.
     *
     * @param node The root node of traversal.
     * @param predicate The predicate.
     * @param collection The collection to fill.
     * @return The filled collection.
     */
    public static Collection collect(Node node,
                                           Predicate predicate,
                                           Collection collection) {
        Checks.isNotNull(node, "node");
        Checks.isNotNull(predicate, "predicate");

        final PredicateCollector visitor = new PredicateCollector(collection, predicate);
        node.accept(visitor);
        return collection;
    }

    @Override
    public Void visitLeaf(AbstractLeafNode node) {
        if (predicate.test(node)) {
            collection.add(node);
        }
        return null;
    }

    @Override
    public Void visitUnary(AbstractUnaryNode node) {
        if (predicate.test(node)) {
            collection.add(node);
        }
        return super.visitUnary(node);
    }

    @Override
    public Void visitBinary(AbstractBinaryNode node) {
        if (predicate.test(node)) {
            collection.add(node);
        }
        return super.visitBinary(node);
    }

    @Override
    public Void visitNary(AbstractNaryNode node) {
        if (predicate.test(node)) {
            collection.add(node);
        }
        return super.visitNary(node);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy