001package jmri.jmrit.logixng.util.parser; 002 003import jmri.JmriException; 004import jmri.jmrit.logixng.SymbolTable; 005import jmri.util.TypeConversionUtil; 006 007/** 008 * A parsed expression 009 */ 010public class ExpressionNodeTernaryOperator implements ExpressionNode { 011 012 private final ExpressionNode _leftSide; 013 private final ExpressionNode _middleSide; 014 private final ExpressionNode _rightSide; 015 016 public ExpressionNodeTernaryOperator( 017 ExpressionNode leftSide, ExpressionNode middleSide, ExpressionNode rightSide) { 018 _leftSide = leftSide; 019 _middleSide = middleSide; 020 _rightSide = rightSide; 021 022 if (_leftSide == null) { 023 throw new IllegalArgumentException("leftSide must not be null"); 024 } 025 } 026 027 @Override 028 public Object calculate(SymbolTable symbolTable) throws JmriException { 029 030 Object leftValue = _leftSide.calculate(symbolTable); 031 if (!(leftValue instanceof Boolean)) { 032 if (TypeConversionUtil.isIntegerNumber(leftValue)) { 033 // Convert to true or false 034 leftValue = ((Number)leftValue).longValue() != 0; 035 } else { 036 throw new CalculateException(Bundle.getMessage("ArithmeticNotBooleanOrIntegerNumberError", leftValue)); 037 } 038 } 039 boolean left = (Boolean)leftValue; 040 041 if (left) { 042 return _middleSide.calculate(symbolTable); 043 } else { 044 return _rightSide.calculate(symbolTable); 045 } 046 } 047 048 /** {@inheritDoc} */ 049 @Override 050 public String getDefinitionString() { 051 return "(" 052 + _leftSide.getDefinitionString() + ")?(" 053 + _middleSide.getDefinitionString() + "):(" 054 + _rightSide.getDefinitionString() + ")"; 055 } 056 057}