com.rabbitmq.jms.parse.ParseTreeTraverser Maven / Gradle / Ivy
/* Copyright (c) 2013 Pivotal Software, Inc. All rights reserved. */
package com.rabbitmq.jms.parse;
/**
* This traverser class encapsulates two methods of traversing a tree, calling a {@link Visitor} for
* each subtree of a {@link ParseTree ParseTree<Node>}.
*
* Each subtree can be visited in ‘pre-order’ as well asO
* in ‘post-order’. ‘Pre-order’ visits each subtree before any of its child subtrees, and ‘post-order’
* visits each subtree after visiting its child subtrees.
*
*
* {@link ParseTreeTraverser#traverse(ParseTree, Visitor)} visits each subtree twice: combining ‘pre-order’ and ‘post-order’ traversal in one pass.
*
*
* The {@link Visitor} contract returns a boolean
flag from its visit methods which these
* traversal algorithms interpret as immediate abort: no further visits will be made after the first returns false.
* Each traversal method returns true
if all the tree is visited, and false
if any visit aborted.
*
*/
public abstract class ParseTreeTraverser { // stop direct instantiation
private ParseTreeTraverser() {}; // stop indirect instantiation
/**
* Visits each subtree in both ‘pre-order’ and ‘post-order’, in one pass.
* Each subtree is visited before (by calling {@link Visitor#visitBefore(Object, Object[])}) and after (by calling {@link Visitor#visitAfter(Object, Object[])})
* all of its child subtrees are visited.
* @param tree the tree all of whose subtrees are to be visited
* @param visitor the {@link Visitor} whose {@link Visitor#visitBefore(Object, Object[])} and {@link Visitor#visitAfter(Object, Object[])}
* methods are passed each subtree’s node and child nodes.
* @return true
if the traversal completed, false
if it was aborted prematurely
*/
public static boolean traverse(ParseTree tree, Visitor visitor) {
if (!visitor.visitBefore(tree.getNode(), tree.getChildNodes())) return false;
for (ParseTree st : tree.getChildren()) {
if (!traverse(st, visitor)) return false;
}
if (!visitor.visitAfter(tree.getNode(), tree.getChildNodes())) return false;
return true;
}
}