cdc.applic.expressions.ast.AbstractBinaryNode 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.
The newest version!
package cdc.applic.expressions.ast;
import java.io.PrintStream;
import java.util.Objects;
import cdc.applic.expressions.Formatting;
import cdc.util.debug.Printables;
import cdc.util.lang.Checks;
/**
* Base class of binary nodes.
*
* @author Damien Carbonne
*/
public abstract class AbstractBinaryNode extends AbstractOperatorNode {
private final Node alpha;
private final Node beta;
private int hash = 0;
protected AbstractBinaryNode(Node alpha,
Node beta) {
Checks.isNotNull(alpha, "alpha");
Checks.isNotNull(beta, "beta");
this.alpha = alpha;
this.beta = beta;
}
public final Node getAlpha() {
return alpha;
}
public final Node getBeta() {
return beta;
}
@Override
public final int getChildrenCount() {
return 2;
}
@Override
public final Node getChildAt(int index) {
if (index == 0) {
return alpha;
} else if (index == 1) {
return beta;
} else {
throw new IllegalArgumentException("Invalid index (" + index + ")");
}
}
public abstract AbstractBinaryNode create(Node alpha,
Node beta);
@Override
public final int getHeight() {
return 1 + Math.max(alpha.getHeight(), beta.getHeight());
}
@Override
public final void buildInfix(Formatting formatting,
StringBuilder builder) {
final boolean alphaParen = needParentheses(getAlpha());
final boolean betaParen = needParentheses(getBeta());
NodeKerning.addOpenParenthese(builder, alphaParen);
getAlpha().buildInfix(formatting, builder);
NodeKerning.addCloseParenthese(builder, alphaParen);
getKerning().addSpace(builder, formatting, alphaParen);
getKerning().addSymbol(builder, formatting);
getKerning().addSpace(builder, formatting, betaParen);
NodeKerning.addOpenParenthese(builder, betaParen);
getBeta().buildInfix(formatting, builder);
NodeKerning.addCloseParenthese(builder, betaParen);
}
@Override
public R accept(Visitor visitor) {
return visitor.visitBinary(this);
}
@Override
public final void print(PrintStream out,
int level) {
Printables.indent(out, level);
out.println(getKind());
getAlpha().print(out, level + 1);
getBeta().print(out, level + 1);
}
@Override
public final boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || !getClass().equals(object.getClass())) {
return false;
}
final AbstractBinaryNode other = (AbstractBinaryNode) object;
return getAlpha().equals(other.getAlpha())
&& getBeta().equals(other.getBeta());
}
@Override
public final int hashCode() {
if (hash == 0) {
hash = Objects.hash(alpha, beta);
}
return hash;
}
@Override
public String toString() {
return getKind() + "(" + getAlpha() + "," + getBeta() + ")";
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy