PragmaHelper.java

package edu.udel.cis.vsl.tass.ast.impl;

import edu.udel.cis.vsl.tass.ast.IF.ASTNodeIF;
import edu.udel.cis.vsl.tass.ast.IF.ASTTransformerIF;
import edu.udel.cis.vsl.tass.ast.IF.AbstractSyntaxTreeIF;
import edu.udel.cis.vsl.tass.ast.IF.statement.PragmaNodeIF;
import edu.udel.cis.vsl.tass.model.IF.SyntaxException;

/**
 * This class prepares the AST for the pragma parser by traversing the AST and
 * setting the next nodes for each pragma node.
 * 
 * @author Timothy Zirkel (zirkel)
 * 
 */
public class PragmaHelper implements ASTTransformerIF {

	public PragmaHelper() {

	}

	@Override
	public void transform(AbstractSyntaxTreeIF ast) throws SyntaxException {
		setNextNodes(ast.rootNode());
	}

	@Override
	public String name() {
		return "Pragma helper";
	}

	/** Returns whether a node is an instance of a PragmaNodeIF. */
	private boolean isPragmaNode(ASTNodeIF node) {
		return node instanceof PragmaNodeIF;
	}

	/**
	 * Examines the children of an AST node. Any pragma has its next node field
	 * set to the next child of this node, with the exception of the final
	 * child. If the final child is a pragma, its next node is left as null.
	 * This method is called recursively on any non-pragma children.
	 */
	private void setNextNodes(ASTNodeIF node) {
		for (int i = 0; i < node.numChildren(); i++) {
			// Note: node.child(i) can be null in some cases.
			if (node.child(i) == null) {
				continue;
			}
			if (isPragmaNode(node.child(i))) {
				if (i != node.numChildren() - 1) {
					((PragmaNodeIF) node.child(i)).setNextNode(node
							.child(i + 1));
				}
			} else {
					setNextNodes(node.child(i));
			}
		}
	}

}