Example #1
0
    private void toString(StringBuffer buff, boolean internal) {
      if (m_children.size() >= 0) {
        if (internal || m_showAndOr) {
          if (m_isAnOr) {
            buff.append("|| ");
          } else {
            buff.append("&& ");
          }
        }

        if (isNegated()) {
          buff.append("!");
        }
        buff.append("(");

        int count = 0;
        for (ExpressionNode child : m_children) {
          if (internal) {
            child.toStringInternal(buff);
          } else {
            child.toStringDisplay(buff);
          }
          count++;
          if (count != m_children.size()) {
            buff.append(" ");
          }
        }
        buff.append(")");
      }
    }
Example #2
0
  protected void evaluateNode(OOEEEvaluationContext context) throws EvaluationException {
    try {
      getValueClass();
    } catch (ParsingException e) {
      throw new EvaluationException(ExceptionConstants.EBOS_000, e);
    }

    ExpressionNode expr = getChild(1);

    expr.evaluate(context);

    Object valueObject = context.stackPop();

    if (ExpressionUtil.isNumeric(valueClass)) {
      try {
        valueObject = ExpressionUtil.getNumericReturnObject(valueObject, valueClass);
      } catch (ParsingException e) {
        throw new EvaluationException(ExceptionConstants.EBOS_000, e);
      }
    } else if (ExpressionUtil.isReferenceType(valueClass)) {
      if (valueObject != null && !valueClass.isAssignableFrom(valueObject.getClass())) {
        throw new EvaluationException(
            ExceptionConstants.EBOS_OOEE_006, new Object[] {valueObject.getClass(), valueClass});
      }
    }

    context.stackPush(valueObject);
  }
Example #3
0
    @Override
    public void init(Instances structure, Environment env) {
      super.init(structure, env);

      for (ExpressionNode n : m_children) {
        n.init(structure, env);
      }
    }
  /**
   * Returns the double value of this operator node operating on its operands.
   *
   * @param parametersValue the value of parameters passed to compute a compiled function.
   * @return the value of this operator.
   */
  public double computeExpression(double[] parametersValue) {
    double number1 = firstOperand.computeExpression(parametersValue);
    double number2 = secondOperand.computeExpression(parametersValue);
    Object binaryOperatorKey = getKey();

    if (binaryOperatorKey.equals(Syntax.OPERATOR_ADD)) return number1 + number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_SUBSTRACT)) return number1 - number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_MULTIPLY)) return number1 * number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_DIVIDE)) return number1 / number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_POWER)) return Math.pow(number1, number2);
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_MODULO)) {
      double modulo = number1 - number2 * (int) (number1 / number2);
      // If dividend and divisor are not of the same sign, add divisor
      if (number1 < 0 && number2 > 0 || number1 > 0 && number2 < 0) modulo += number2;
      return modulo;
    } else if (binaryOperatorKey.equals(Syntax.OPERATOR_REMAINDER)) return number1 % number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_EQUAL))
      return number1 == number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_DIFFERENT))
      return number1 != number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_GREATER_OR_EQUAL))
      return number1 >= number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_LESS_OR_EQUAL))
      return number1 <= number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_GREATER))
      return number1 > number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_LESS))
      return number1 < number2 ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_LOGICAL_OR))
      return number1 != FALSE_DOUBLE || number2 != FALSE_DOUBLE ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_LOGICAL_AND))
      return number1 != FALSE_DOUBLE && number2 != FALSE_DOUBLE ? TRUE_DOUBLE : FALSE_DOUBLE;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_LOGICAL_XOR))
      return number1 != FALSE_DOUBLE && number2 == FALSE_DOUBLE
              || number1 == FALSE_DOUBLE && number2 != FALSE_DOUBLE
          ? TRUE_DOUBLE
          : FALSE_DOUBLE;
    else if (Math.floor(number1) != number1)
      throw new IllegalArgumentException("Operand " + number1 + " of bit operator not an integer");
    else if (Math.floor(number2) != number2)
      throw new IllegalArgumentException("Operand " + number2 + " of bit operator not an integer");
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_BITWISE_OR))
      return (long) number1 | (long) number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_BITWISE_XOR))
      return (long) number1 ^ (long) number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_BITWISE_AND))
      return (long) number1 & (long) number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_SHIFT_LEFT))
      return (long) number1 << (long) number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_SHIFT_RIGHT))
      return (long) number1 >> (long) number2;
    else if (binaryOperatorKey.equals(Syntax.OPERATOR_SHIFT_RIGHT_0))
      return (long) number1 >>> (long) number2;
    else
      // User binary operators must be implemented in an interpreter
      throw new IllegalArgumentException(
          "Binary operator key " + binaryOperatorKey + " not implemented");
  }
 @Override
 public boolean accept(ExpressionVisitor v) {
   if (v.visitEnter(this)) {
     for (ExpressionNode operand : operands) {
       if (!operand.accept(v)) break;
     }
   }
   return v.visitLeave(this);
 }
  private void doPrintTree(ExpressionNode node, int depth) {
    if (node != null) {
      if (node.getLeftChild() != null) {
        doPrintTree(node.getLeftChild(), depth + 1);
      }

      if (node.getRightChild() != null) {
        doPrintTree(node.getRightChild(), depth + 1);
      }
    }
  }
Example #7
0
 private void pushNode(Node node) {
   RootEntry entry = getCurrentRoot();
   if (entry.root == null) entry.root = node;
   else {
     ExpressionNode enode = (ExpressionNode) entry.root;
     if (enode.opcode == OP_NOT) enode.right = node;
     else {
       if (enode.left == null) enode.left = node;
       else enode.right = node;
     }
   }
 }
 /**
  * Returns the value of the sub-expression that is rooted at this node.
  *
  * <p>Calculates base^exponent
  */
 public Object getValue() {
   Object baseValue = applyType(base.getValue());
   Object exponentValue = applyType(exponent.getValue());
   if (baseValue instanceof Double && exponentValue instanceof Double) {
     return Math.pow((Double) baseValue, (Double) exponentValue);
   } else {
     throw new EvaluationException(
         "Exponentiation accepted between two numbers, but found instead "
             + baseValue
             + " and "
             + exponentValue);
   }
 }
Example #9
0
  // replace every x in tree by (x - vx)
  // i.e. replace fVar with (fvar - vx)
  private void translateX(ExpressionNode en, double vx, int varNo) {
    ExpressionValue left = en.getLeft();
    ExpressionValue right = en.getRight();

    // left tree
    if (left == fVars[varNo]) {
      try { // is there a constant number to the right?
        MyDouble num = (MyDouble) right;
        double temp;
        switch (en.getOperation()) {
          case ExpressionNode.PLUS:
            temp = num.getDouble() - vx;
            if (Kernel.isZero(temp)) {
              expression = expression.replaceAndWrap(en, fVars[varNo]);
            } else if (temp < 0) {
              en.setOperation(ExpressionNode.MINUS);
              num.set(-temp);
            } else {
              num.set(temp);
            }
            return;

          case ExpressionNode.MINUS:
            temp = num.getDouble() + vx;
            if (Kernel.isZero(temp)) {
              expression = expression.replaceAndWrap(en, fVars[varNo]);
            } else if (temp < 0) {
              en.setOperation(ExpressionNode.PLUS);
              num.set(-temp);
            } else {
              num.set(temp);
            }
            return;

          default:
            en.setLeft(shiftXnode(vx, varNo));
        }
      } catch (Exception e) {
        en.setLeft(shiftXnode(vx, varNo));
      }
    } else if (left instanceof ExpressionNode) {
      translateX((ExpressionNode) left, vx, varNo);
    }

    // right tree
    if (right == fVars[varNo]) {
      en.setRight(shiftXnode(vx, varNo));
    } else if (right instanceof ExpressionNode) {
      translateX((ExpressionNode) right, vx, varNo);
    }
  }
Example #10
0
    @Override
    public DefaultMutableTreeNode toJTree(DefaultMutableTreeNode parent) {

      DefaultMutableTreeNode current = new DefaultMutableTreeNode(this);
      if (parent != null) {
        parent.add(current);
      }

      for (ExpressionNode child : m_children) {
        child.toJTree(current);
      }

      return current;
    }
Example #11
0
    @Override
    public boolean evaluate(Instance inst, boolean result) {

      boolean thisNode = true;
      if (m_children.size() > 0) {
        for (ExpressionNode n : m_children) {
          thisNode = n.evaluate(inst, thisNode);
        }
        if (isNegated()) {
          thisNode = !thisNode;
        }
      }

      return (isOr() ? (result || thisNode) : (result && thisNode));
    }
Example #12
0
 private boolean initIneqs(
     ExpressionNode fe, FunctionalNVar functional, IneqTree tree, boolean negate) {
   int op = fe.getOperation();
   ExpressionNode leftTree = fe.getLeftTree();
   ExpressionNode rightTree = fe.getRightTree();
   if (op == ExpressionNode.GREATER
       || op == ExpressionNode.GREATER_EQUAL
       || op == ExpressionNode.LESS
       || op == ExpressionNode.LESS_EQUAL) {
     Inequality newIneq =
         new Inequality(
             kernel,
             leftTree,
             rightTree,
             adjustOp(op, negate),
             getFunction().getFunctionVariables(),
             functional);
     if (newIneq.getType() != Inequality.INEQUALITY_INVALID) {
       if (newIneq.getType() != Inequality.INEQUALITY_1VAR_X
           && newIneq.getType() != Inequality.INEQUALITY_1VAR_Y)
         newIneq.getBorder().setInverseFill(newIneq.isAboveBorder());
       tree.setIneq(newIneq);
     }
     return newIneq.getType() != Inequality.INEQUALITY_INVALID;
   } else if (op == ExpressionNode.AND
       || op == ExpressionNode.OR
       || op == ExpressionNode.EQUAL_BOOLEAN
       || op == ExpressionNode.NOT_EQUAL) {
     tree.operation = adjustOp(op, negate);
     tree.left = new IneqTree();
     tree.right = new IneqTree();
     return initIneqs(leftTree, functional, tree.left, negate)
         && initIneqs(rightTree, functional, tree.right, negate);
   } else if (op == ExpressionNode.NOT) {
     return initIneqs(leftTree, functional, tree, !negate);
   } else if (op == ExpressionNode.FUNCTION_NVAR) {
     FunctionalNVar nv = (FunctionalNVar) leftTree.getLeft();
     IneqTree otherTree = nv.getIneqs();
     if (otherTree == null || otherTree.getSize() == 0) {
       return false;
     }
     tree.left = otherTree.left;
     tree.right = otherTree.right;
     tree.operation = otherTree.operation;
     tree.ineq = otherTree.ineq;
     return true;
   } else return false;
 }
  public boolean evaluate(ServiceType service) throws ParseExpressionException {
    if (rootNode == null) {
      rootNode = parse();
    }

    return rootNode.evaluate(service, miOntologyTree);
  }
Example #14
0
  /**
   * Initialize with respect to the incoming instance format
   *
   * @param data the incoming instance format
   */
  protected void init(Instances data) {
    m_indexOfTrueStep = -1;
    m_indexOfFalseStep = -1;
    m_connectedFormat = data;

    if (m_downstream == null) {
      return;
    }

    if (m_downstream[0] != null
        && ((BeanCommon) m_downstream[0]).getCustomName().equals(m_customNameOfTrueStep)) {
      m_indexOfTrueStep = 0;
    }
    if (m_downstream[0] != null
        && ((BeanCommon) m_downstream[0]).getCustomName().equals(m_customNameOfFalseStep)) {
      m_indexOfFalseStep = 0;
    }

    if (m_downstream[1] != null
        && ((BeanCommon) m_downstream[1]).getCustomName().equals(m_customNameOfTrueStep)) {
      m_indexOfTrueStep = 1;
    }
    if (m_downstream[1] != null
        && ((BeanCommon) m_downstream[1]).getCustomName().equals(m_customNameOfFalseStep)) {
      m_indexOfFalseStep = 1;
    }

    if (m_env == null) {
      m_env = Environment.getSystemWide();
    }

    try {
      if (m_expressionString != null && m_expressionString.length() > 0) {
        m_root = new BracketNode();
        m_root.parseFromInternal(m_expressionString);
      }
      if (m_root != null) {
        m_root.init(data, m_env);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      stop();
      m_busy = false;
    }
  }
Example #15
0
 /**
  * 此方法,将root涉及到的符号变量初始化为约束求解中的基本变量
  *
  * @param root
  */
 public void updateVariableAndPrintExpression(ExpressionNode root) {
   HashMap<ExpressionOperator, String> expression_operator = new HashMap<>();
   expression_operator.put(ExpressionOperator.div, "\\");
   expression_operator.put(ExpressionOperator.plus, "+");
   expression_operator.put(ExpressionOperator.minus, "-");
   expression_operator.put(ExpressionOperator.multi, "*");
   if (root != null) {
     //			if(root.operator!=null){
     if (root.getType() == ExpressionType.expression) {
       print("(");
       updateVariable(root.getLeft());
       //				print(root.getOperator());
       print(expression_operator.get(root.getOperator()));
       updateVariable(root.getRight());
       print(")");
     } else {
       print(root.getValue());
       if (root.getType() == ExpressionType.single_variable) {
         String variableName = root.getValue();
         if (!envVariableValueHashMap.containsKey(variableName)) {
           envVariableValueHashMap.put(variableName, Choco.makeIntVar(variableName));
         }
       }
     }
   }
 }
Example #16
0
 public void matrixTransform(
     double a00,
     double a01,
     double a02,
     double a10,
     double a11,
     double a12,
     double a20,
     double a21,
     double a22) {
   ExpressionNode dummy = new ExpressionNode();
   expression = expression.replaceAndWrap(fVars[0], dummy);
   double[][] b = MyMath.adjoint(a00, a01, a02, a10, a11, a12, a20, a21, a22);
   MyDouble[][] mbTrans = new MyDouble[3][3];
   for (int i = 0; i < 3; i++)
     for (int j = 0; j < 3; j++) mbTrans[i][j] = new MyDouble(kernel, b[j][i]);
   ExpressionNode newZ =
       new ExpressionNode(kernel, mbTrans[2][0], ExpressionNode.MULTIPLY, fVars[0])
           .plus(new ExpressionNode(kernel, mbTrans[2][1], ExpressionNode.MULTIPLY, fVars[1]))
           .plus(mbTrans[2][2]);
   ExpressionNode newX =
       new ExpressionNode(kernel, mbTrans[0][0], ExpressionNode.MULTIPLY, fVars[0])
           .plus(new ExpressionNode(kernel, mbTrans[0][1], ExpressionNode.MULTIPLY, fVars[1]))
           .plus(mbTrans[0][2]);
   ExpressionNode newY =
       new ExpressionNode(kernel, mbTrans[1][0], ExpressionNode.MULTIPLY, fVars[0])
           .plus(new ExpressionNode(kernel, mbTrans[1][1], ExpressionNode.MULTIPLY, fVars[1]))
           .plus(mbTrans[1][2]);
   expression = expression.replaceAndWrap(fVars[1], newY.divide(newZ));
   expression = expression.replaceAndWrap(dummy, newX.divide(newZ));
   this.initIneqs(expression, this);
 }
Example #17
0
  public void matrixTransform(double a00, double a01, double a10, double a11) {
    ExpressionNode dummy = new ExpressionNode();
    expression.replaceAndWrap(fVars[0], dummy);
    MyDouble ma00 = new MyDouble(kernel, a00);
    MyDouble ma01 = new MyDouble(kernel, a01);
    MyDouble ma10 = new MyDouble(kernel, a10);
    MyDouble ma11 = new MyDouble(kernel, a11);

    ExpressionNode newX =
        new ExpressionNode(kernel, ma00, ExpressionNode.MULTIPLY, fVars[0])
            .plus(new ExpressionNode(kernel, ma01, ExpressionNode.MULTIPLY, fVars[1]));
    ExpressionNode newY =
        new ExpressionNode(kernel, ma10, ExpressionNode.MULTIPLY, fVars[0])
            .plus(new ExpressionNode(kernel, ma11, ExpressionNode.MULTIPLY, fVars[1]));
    expression = expression.replaceAndWrap(fVars[1], newY);
    expression = expression.replaceAndWrap(dummy, newX);
    this.initIneqs(expression, this);
  }
Example #18
0
  public void translate(double vx, double vy) {

    // translate x
    if (!Kernel.isZero(vx)) {
      translateX(expression, vx, 0);
    }
    if (!Kernel.isZero(vy)) {
      translateX(expression, vy, 1);
    }

    // make sure that expression object is changed!
    // this is needed to know that the expression has changed
    if (expression.isLeaf() && expression.getLeft().isExpressionNode()) {
      expression = new ExpressionNode((ExpressionNode) expression.getLeft());
    } else {
      expression = new ExpressionNode(expression);
    }
  }
Example #19
0
  public Class checkType(OOEEParsingContext context) throws ParsingException {
    ExpressionNode expr = getChild(0);
    Class exprClass = expr.checkType(context);

    ExpressionNode type = getChild(1);
    Class instanceClass = type.checkType(context);

    if (!ExpressionUtil.isReferenceType(exprClass)
        || !ExpressionUtil.isReferenceType(instanceClass)
        || !ExpressionUtil.isCastableFrom(instanceClass, exprClass)) {
      throw new ParsingException(
          ExceptionConstants.EBOS_OOEE_037, new Object[] {exprClass, instanceClass});
    }

    instanceClassName = instanceClass.getName();
    setValueClass(boolean.class);

    return valueClass;
  }
Example #20
0
    @Override
    protected String parseFromInternal(String expression) {
      if (expression.startsWith("|| ")) {
        m_isAnOr = true;
      }

      if (expression.startsWith("|| ") || expression.startsWith("&& ")) {
        expression = expression.substring(3, expression.length());
      }

      if (expression.charAt(0) == '!') {
        setNegated(true);
        expression = expression.substring(1, expression.length());
      }

      if (expression.charAt(0) != '(') {
        throw new IllegalArgumentException("Malformed expression! Was expecting a \"(\"");
      }

      expression = expression.substring(1, expression.length());

      while (expression.charAt(0) != ')') {
        int offset = 3;

        if (expression.charAt(offset) == '(') {
          ExpressionNode child = new BracketNode();
          expression = child.parseFromInternal(expression);
          m_children.add(child);
        } else {
          // must be an ExpressionClause
          ExpressionNode child = new ExpressionClause();
          expression = child.parseFromInternal(expression);
          m_children.add(child);
        }
      }

      if (m_children.size() > 0) {
        m_children.get(0).setShowAndOr(false);
      }

      return expression;
    }
Example #21
0
  /**
   * Tries to fix a structural problem leading to an evaluation error, e.g. x(x+1) is interpreted as
   * xcoord(x+1). This can be fixed by changing the structure to x*(x+1) for example.
   */
  private void fixStructure() {
    // get function variables for x, y, z
    FunctionVariable xVar = null, yVar = null, zVar = null;
    for (FunctionVariable fVar : fVars) {
      if ("x".equals(fVar.toString())) xVar = fVar;
      else if ("y".equals(fVar.toString())) yVar = fVar;
      else if ("z".equals(fVar.toString())) zVar = fVar;
    }

    // try to replace x(x+1) by x*(x+1)
    expression.replaceXYZnodes(xVar, yVar, zVar);
  }
  protected void doValidate(ExpressionNode e, Expect et, boolean types) {
    Object toCompare; // comparing types or expressions
    if (types) toCompare = e.get_type();
    else toCompare = e.getClass();

    boolean matched = false;
    try {
      // top level exp/type must match expected
      if (types) {
        assertTrue(((TypeNode) toCompare).equal_types((TypeNode) (et.expected)));
      } else assertTrue(toCompare.equals(et.expected));
      matched = true;
      // look at sub expressions
      // subexpression counts must match OR we are testing less than is
      // there
      assertTrue(et.subCount() <= e.childCount());
    } catch (AssertionFailedError afe) {
      if (!matched) {
        String actual, expected;
        if (types) {
          actual = ((TypeNode) toCompare).typeId();
          expected = ((TypeNode) et.expected).typeId();
        } else {
          actual = ((Class) toCompare).getName();
          expected = ((Class) et.expected).getName();
        }
        d.msg(Debug.COMPILE, "Expecting " + expected + ", got " + actual);
      } else {
        d.msg(
            Debug.COMPILE, "Have " + e.childCount() + " subexpressions, expected " + et.subCount());
      }
      throw afe;
    }

    for (int i = 0; i < et.subCount(); i++) {
      ExpressionNode currExp = e.child_exp(i);
      Expect currC = et.sub(i);
      doValidate(currExp, currC, types);
    }
  }
Example #23
0
  @Override
  public void acceptDataSet(DataSetEvent e) {

    m_busy = true;
    if (m_log != null && !e.isStructureOnly()) {
      m_log.statusMessage(statusMessagePrefix() + "Processing batch...");
    }

    init(new Instances(e.getDataSet(), 0));

    if (m_root != null) {
      Instances trueBatch = new Instances(e.getDataSet(), 0);
      Instances falseBatch = new Instances(e.getDataSet(), 0);

      for (int i = 0; i < e.getDataSet().numInstances(); i++) {
        Instance current = e.getDataSet().instance(i);

        boolean result = m_root.evaluate(current, true);

        if (result) {
          if (m_indexOfTrueStep >= 0) {
            trueBatch.add(current);
          }
        } else {
          if (m_indexOfFalseStep >= 0) {
            falseBatch.add(current);
          }
        }
      }

      if (m_indexOfTrueStep >= 0) {
        DataSetEvent d = new DataSetEvent(this, trueBatch);
        ((DataSourceListener) m_downstream[m_indexOfTrueStep]).acceptDataSet(d);
      }

      if (m_indexOfFalseStep >= 0) {
        DataSetEvent d = new DataSetEvent(this, falseBatch);
        ((DataSourceListener) m_downstream[m_indexOfFalseStep]).acceptDataSet(d);
      }
    } else {
      if (m_indexOfTrueStep >= 0) {
        DataSetEvent d = new DataSetEvent(this, e.getDataSet());
        ((DataSourceListener) m_downstream[m_indexOfTrueStep]).acceptDataSet(d);
      }
    }

    if (m_log != null && !e.isStructureOnly()) {
      m_log.statusMessage(statusMessagePrefix() + "Finished");
    }

    m_busy = false;
  }
Example #24
0
 /**
  * Returns this function's value at position.
  *
  * @param vals
  * @return f(vals)
  */
 public final double evaluate(double[] vals) {
   if (isBooleanFunction) {
     // BooleanValue
     return evaluateBoolean(vals) ? 1 : 0;
   } else {
     // NumberValue
     for (int i = 0; i < fVars.length; i++) {
       // Application.debug(fVars[i].toString()+" <= "+vals[i]);
       fVars[i].set(vals[i]);
     }
     return ((NumberValue) expression.evaluate()).getDouble();
   }
 }
Example #25
0
  protected void evaluateNode(OOEEEvaluationContext context) throws EvaluationException {
    try {
      getValueClass();
    } catch (ParsingException e) {
      throw new EvaluationException(ExceptionConstants.EBOS_000, e);
    }

    Class instanceClass = null;
    try {
      instanceClass = ExpressionUtil.findClass(instanceClassName);
    } catch (ParsingException e) {
      throw new EvaluationException(ExceptionConstants.EBOS_000, e);
    }

    ExpressionNode expr = getChild(0);

    expr.evaluate(context);

    Object exprObject = context.stackPop();

    Object valueObject = instanceClass.isInstance(exprObject) ? Boolean.TRUE : Boolean.FALSE;

    context.stackPush(valueObject);
  }
Example #26
0
  public AbstractDatum inner_step(ExpressionNode nd, VMState vms) {
    // Find the object
    Object xd = vms.top().at(nd.child_exp(0));
    Assert.check(xd instanceof AbstractPointerDatum);
    AbstractPointerDatum xpd = (AbstractPointerDatum) xd;
    AbstractDatum rd = (AbstractDatum) xpd.deref();
    Assert.check(rd instanceof AbstractObjectDatum);
    AbstractObjectDatum object = (AbstractObjectDatum) rd;

    // Find the field
    AbstractDatum field = object.getFieldByName(((OpMember) nd).path, ((OpMember) nd).member);

    // New datum on scratch
    Clc_ASTUtilities util = (Clc_ASTUtilities) vms.getProperty("ASTUtilities");
    AbstractRefDatum d = (AbstractRefDatum) util.scratchDatum(nd.get_type(), vms);

    // Give it a value
    d.putValue(field);
    String name =
        xpd.getValueString() + ((OpMember) nd).operator_image + ((OpMember) nd).member_name;
    d.putValueString(name);

    return d;
  }
Example #27
0
  /**
   * Call this function to resolve variables and init the function. May throw MyError
   * (InvalidFunction).
   */
  public void initFunction() {
    // replace function variables in tree
    for (int i = 0; i < fVars.length; i++) {
      FunctionVariable fVar = fVars[i];

      // look for Variable objects with name of function variable and
      // replace them
      int replacements = expression.replaceVariables(fVar.getSetVarString(), fVar);
      isConstantFunction = isConstantFunction && replacements == 0;

      if (replacements == 0) {
        // x, y got polynomials while parsing
        replacements = expression.replacePolynomials(fVar);
        isConstantFunction = isConstantFunction && replacements == 0;
      }
    }

    // replace variable names by objects
    expression.resolveVariables();

    // the idea here was to allow something like: Derivative[f] + 3x
    // but wrapping the GeoFunction objects as ExpressionNodes of type
    // FUNCTION
    // leads to Derivative[f](x) + 3x
    // expression.wrapGeoFunctionsAsExpressionNode();

    // replace all polynomials in expression (they are all equal to "1x" if
    // we got this far)
    // by an instance of MyDouble

    // simplify constant parts in expression
    expression.simplifyConstantIntegers();

    // evaluate expression to find out about the type of function
    ExpressionValue ev;
    try {
      ev = expression.evaluate();
    } catch (MyError err) {
      // Evaluation failed: DESPERATE MODE
      try {
        // try to fix structure of expression and then try evaluation again
        fixStructure();
        ev = expression.evaluate();
      } catch (Throwable th) {
        // throw original error when desperate mode failed
        throw err;
      }
    }

    // initialize type as boolean or numeric function
    initType(ev);
  }
Example #28
0
 private void initType(ExpressionValue ev) {
   if (ev.isBooleanValue()) {
     isBooleanFunction = true;
   } else if (ev.isNumberValue()) {
     isBooleanFunction = false;
   } else if (ev instanceof FunctionNVar) {
     expression = ((FunctionNVar) ev).getExpression();
     fVars = ((FunctionNVar) ev).getFunctionVariables();
   } else {
     Application.debug(
         "InvalidFunction:"
             + expression.toString()
             + " "
             + ev.toString()
             + ev.getClass().getName());
     throw new MyError(kernel.getApplication(), "InvalidFunction");
   }
 }
  protected void validate(ExpressionNode e, Object expC, Object[][] opCs, boolean types) {
    Object toCompare; // comparing types or expressions
    if (types) toCompare = e.get_type();
    else toCompare = e.getClass();

    // top level exp/type must match expC
    if (types) {
      assertTrue(((TypeNode) toCompare).equal_types((TypeNode) (expC)));
    } else assertTrue(toCompare.equals(expC));

    // look at operands
    for (int i = 0; i < opCs.length; i++) {
      // looking at operand [i]
      ExpressionNode currExp = e.child_exp(i);
      for (int j = 0; j < opCs[i].length; j++) {

        toCompare = (types) ? (Object) currExp.get_type() : (Object) currExp.getClass();

        try {
          if (types) {
            assertTrue(((TypeNode) toCompare).equal_types((TypeNode) (opCs[i][j])));
          } else assertTrue(toCompare.equals(opCs[i][j]));

        } catch (AssertionFailedError afe) {
          String actual, expected;
          if (types) {
            actual = ((TypeNode) toCompare).typeId();
            expected = ((TypeNode) opCs[i][j]).typeId();
          } else {
            actual = ((Class) toCompare).getName();
            expected = ((Class) opCs[i][j]).getName();
          }
          d.msg(Debug.COMPILE, "Expecting " + expected + ", got " + actual);
          throw afe;
        }

        if (currExp.childCount() > 0) currExp = currExp.child_exp(0);
        else break;
      }
    }
  }
Example #30
0
  @Override
  public void buildString(StringBuilder builder, int tabs) {
    builder.append("AssignmentNode\n");

    for (int i = 0; i < tabs; i++) {
      builder.append("\t");
    }
    builder.append(identifier + "\n");

    for (int i = 0; i < tabs; i++) {
      builder.append("\t");
    }
    builder.append(assign + "\n");
    for (int i = 0; i < tabs; i++) {
      builder.append("\t");
    }
    expn.buildString(builder, tabs + 1);
    for (int i = 0; i < tabs; i++) {
      builder.append("\t");
    }
    builder.append(semicolon + "\n");
  }