Пример #1
0
  /**
   * Parses the expression. If there are errors in the expression, they are added to the <code>
   * errorList</code> member. Errors can be obtained through <code>getErrorInfo()</code>.
   *
   * @param expression_in The input expression string
   * @return the top node of the expression tree if the parse was successful, <code>null</code>
   *     otherwise
   */
  public Node parseExpression(String expression_in) {
    Reader reader = new StringReader(expression_in);

    try {
      // try parsing
      errorList.removeAllElements();
      topNode = parser.parseStream(reader, this);

      // if there is an error in the list, the parse failed
      // so set topNode to null
      if (hasError()) topNode = null;
    } catch (Throwable e) {
      // an exception was thrown, so there is no parse tree
      topNode = null;

      // check the type of error
      if (e instanceof ParseException) {
        // the ParseException object contains additional error
        // information
        errorList.addElement(((ParseException) e).getMessage());
        // getErrorInfo());
      } else {
        // if the exception was not a ParseException, it was most
        // likely a syntax error
        if (debug) {
          System.out.println(e.getMessage());
          e.printStackTrace();
        }
        errorList.addElement("Syntax error");
      }
    }

    // If traversing is enabled, print a dump of the tree to
    // standard output
    if (traverse && !hasError()) {
      ParserVisitor v = new ParserDumpVisitor();
      try {
        topNode.jjtAccept(v, null);
      } catch (ParseException e) {
        errorList.addElement(e.getMessage());
      }
    }

    return topNode;
  }
Пример #2
0
  /**
   * Evaluates and returns the value of the expression as an object. The EvaluatorVisitor member ev
   * is used to do the evaluation procedure. This method is useful when the type of the value is
   * unknown, or not important.
   *
   * @return The calculated value of the expression if no errors occur. Returns null otherwise.
   */
  public Object getValueAsObject() {
    Object result;

    if (topNode == null) return null;
    // evaluate the expression
    try {
      result = ev.getValue(topNode, symTab);
    } catch (ParseException e) {
      if (debug) System.out.println(e);
      errorList.addElement("Error during evaluation: " + e.getMessage());
      return null;
    } catch (RuntimeException e) {
      if (debug) System.out.println(e);
      errorList.addElement(e.getClass().getName() + ": " + e.getMessage());
      return null;
    }
    return result;
  }