Evaluates once parsed to a lambda term

@return <code>String</code> representation of the result
@throws <code>ParseException</code> if the input expression is not
correct
@since 3.0
358463
private RLSupplier<Value> evaluate() {
		/* check if is there something to evaluate */
        if (stackRPN.empty()) {
            return () -> new StringValue("");
        }

		/* clean answer stack */
        stackAnswer.clear();

		/* get the clone of the RPN stack for further evaluating */
        @SuppressWarnings("unchecked")
        Stack stackRPN = (Stack) this.stackRPN.clone();

		/* evaluating the RPN expression */
        while (!stackRPN.empty()) {
            Object token = stackRPN.pop();
            if (token instanceof Value) {
                stackAnswer.push( (RLSupplier) ()->token );
            } else if (token instanceof Operator) {
                int arity = ((Operator) token).getArity();
                if ( arity == 2 ) {
                    RLSupplier a = (RLSupplier) stackAnswer.pop();
                    RLSupplier b = (RLSupplier) stackAnswer.pop();
                    stackAnswer.push( ((Operator) token).getEval(a,b));
                } else { // assume 1
                    RLSupplier a = (RLSupplier) stackAnswer.pop();
                    stackAnswer.push( ((Operator) token).getEval(a,null));
                }
            } else if (token instanceof VarPath) {
                VarPath vp = (VarPath) token;
                stackAnswer.push( vp.getEval() );
            } else if (token instanceof FuncOperand) {
                FuncOperand func = (FuncOperand) token;
                RLSupplier<Value> args[] = new RLSupplier[func.getArity()];
                for (int i = 0; i < args.length; i++) {
                    args[args.length-i-1] = ((RLSupplier<Value>)stackAnswer.pop());
                }
                stackAnswer.push(func.getEval(args));
            }
        }

        if (stackAnswer.size() > 1) {
            throw new QParseException("Some operator is missing");
        }

        return (RLSupplier<Value>) stackAnswer.pop();
    }
1036735
public QueryBuilderKraken parse()
  {
    Token token = scanToken();

    switch (token) {
    case CREATE:
      return parseCreate();
      
    case EXPLAIN:
      return parseExplain();

    case INSERT:
      return parseInsert();

    case REPLACE:
      return parseReplace();
      
    case SELECT:
      return parseSelect();
      
    case SELECT_LOCAL:
      return parseSelectLocal();
      
    case MAP:
      return parseMap();
      
    case SHOW:
      return parseShow();
      
    case UPDATE:
      return parseUpdate();
      
    case DELETE:
      return parseDelete();
      
    case WATCH:
      return parseWatch();
      
      /*
    case NOTIFY:
      return parseNotify();
      */

      /*
    case VALIDATE:
      return parseValidate();

    case DROP:
      return parseDrop();
*/
      
    case IDENTIFIER:
      if (_lexeme.equalsIgnoreCase("checkpoint")) {
        return parseCheckpoint();
      }
      
    default:
      throw error("unknown query at {0}", token);
    }
  }
948541
@Override
    protected void parseDataDefinition(StreamTokenizer streamTokenizer) throws FSMParseException, IOException {
        if (acceptIndex == -1 && acceptValue == -1) {

            // check we will read an identifier.
            if (streamTokenizer.nextToken() != StreamTokenizer.TT_WORD) {
                throw new FSMParseException(EXPECT_IDENTIFIER, streamTokenizer);
            }

            final String dataVariableName = streamTokenizer.sval;

            if (dataVariableName.equals(acceptingDataVariableName)) {
                acceptIndex = getPartLineNumber();

                // skip a (
                if (streamTokenizer.nextToken() != '(') {
                    throw new FSMParseException(String.format(EXPECT_CHAR, '('), streamTokenizer);
                }

                // skip a number
                if (streamTokenizer.nextToken() != StreamTokenizer.TT_WORD) {
                    throw new FSMParseException(EXPECT_NUMBER, streamTokenizer);
                }

                // skip a )
                if (streamTokenizer.nextToken() != ')') {
                    throw new FSMParseException(String.format(EXPECT_CHAR, ')'), streamTokenizer);
                }

                // skip an identifier
                if (streamTokenizer.nextToken() != StreamTokenizer.TT_WORD) {
                    throw new FSMParseException(EXPECT_IDENTIFIER, streamTokenizer);
                }

                int dataValueIndex = 0;

                // find the string containing the acceptance information
                while (streamTokenizer.nextToken() == '"' && acceptValue == -1) {
                    final String dataValue = streamTokenizer.sval;
                    if (dataValue.equals(acceptingDataValue)) {
                        acceptValue = dataValueIndex;
                    } else {
                        dataValueIndex++;
                    }
                }
                // push back the EOL, or EOF we accidentally read
                streamTokenizer.pushBack();

                // throw an Exception when the string containing acceptance information is not found in the current line
                if (acceptValue == -1) {
                    throw new FSMParseException(String.format(ACCEPT_VALUE_NOT_FOUND, acceptingDataValue),
                                                streamTokenizer);
                }
            }
        }
    }
803585
private Node parseResultType() {
    skipEOLs();
    if (!match(JsDocToken.COLON)) {
      return newNode(Token.EMPTY);
    }

    next();
    skipEOLs();
    if (match(JsDocToken.STRING) && "void".equals(stream.getString())) {
      next();
      return newNode(Token.VOID);
    } else {
      return parseTypeExpression(next());
    }
  }
782433
@Override
  public List<String> parse() throws ParseException {

    if (expression == null)
      throw new ParseException("The expression is null", -1);

    if (logger.isDebugEnabled())
      logger.debug("Expression: " + expression);

    // expression is empty, nothing we can do
    if (expression.length() < 1)
      return null;

    // no question marks, nothing to do
    if (!expression.contains("?")) {
      return null;
    }

    // upper case the expression, to make things easier
    expression = expression.toUpperCase();

    List<String> colList = new ArrayList<>();

    if (expression.startsWith("INSERT")) {
      // expression is in the format of:  insert into table(col1, col2...) values(val1, val2...)
      // so we'll use the parens () to parse

      int colParenStart = expression.indexOf("(");
      if (colParenStart == -1)
        throw new ParseException("Unable to locate starting parenthesis for the column names.", -1);

      int colParenEnd = expression.indexOf(")", colParenStart);
      if (colParenEnd == -1)
        throw new ParseException("Unable to locate ending parenthesis for the column names.", -1);

      int valParenStart = expression.indexOf("(", colParenEnd);
      if (valParenStart == -1)
        throw new ParseException("Unable to locate starting parenthesis for the column values.", -1);

      // use the last close paren, this will make weird inner select stuff work,
      // but it won't be able to guess the inner select values
      int valParenEnd = expression.lastIndexOf(")");
      if (valParenEnd == -1)
        throw new ParseException("Unable to locate ending parenthesis for the column values.", -1);

      String[] cols = expression.substring(colParenStart + 1, colParenEnd).split(",");
      String[] vals = expression.substring(valParenStart + 1, valParenEnd).split(",");

      // if cols or vals is null, it means we couldn't find any
      if (cols == null || vals == null)
        return null;

      if (logger.isDebugEnabled()) {
        logger.debug("Found cols: " + cols.length);
        logger.debug("Found vals: " + vals.length);
      }

      if (cols.length != vals.length)
        throw new ParseException("You seem to have " + cols.length + " columns, and " + vals.length + " values.\n\nThose numbers should be equal.", -1);

      // filter out columns that we're not providing values for
      for (int i = 0; i < vals.length; i++) {
        String val = vals[i];
        if (val.trim().equals("?")) {
          // just a ?, use the col
          colList.add(cols[i].trim());
        } else if (val.contains("?")) {
          // more than just a ?, parse the val
          ExpressionParser qp = new BoundExpressionParser();
          qp.setExpression(val);
          colList.addAll(qp.parse());
        }
      }
    } else {
      // expression is in the format of:  ...col1 = ? , col2 = ?...
      // so we'll have to move left to right from the ? looking for the field name

      int startIdx = 0;
      Collection<Integer> indexes = getArgumentIndexes();
      for (int qIdx : indexes) {
        String chunk = expression.substring(startIdx, qIdx);

        if (logger.isDebugEnabled())
          logger.debug("Chunk [" + chunk + "]");

        int idx = chunk.length() - 1;
        int fieldStartIdx = -1;
        int fieldEndIdx = -1;

        boolean found = false;
        boolean inFunction = false;
        while (!found && (idx >= 0)) {
          char c = chunk.charAt(idx);

          if (fieldEndIdx == -1) {
            // if the character is a ( this might be a function like UPPER(), try to parse that out
            if (!inFunction && c == '(') {
              inFunction = true;
            } else if (inFunction && COMPARE_CHARS.indexOf(c) != -1) {
              inFunction = false;
            }

            // till we find the first char of the end of the field name, ignore compare chars
            if (!inFunction && COMPARE_CHARS.indexOf(c) == -1) {
              // found a char, must be the end of the field name
              fieldEndIdx = idx;
            }
          } else {
            // if we find a separator, we've reached the beginning of the field name
            if (SEPARATOR_CHARS.indexOf(c) >= 0) {
              fieldStartIdx = idx + 1;
              found = true;
            }
          }
          idx--;
        }
        if (found) {
          String col = chunk.substring(fieldStartIdx, fieldEndIdx + 1);
          colList.add(col);
        }

        // move the starting index to where the ? was
        startIdx = qIdx + 1;
      }
    }

    return colList;
  }
936959
public SoyExpression coerceToString() {
    if (soyRuntimeType.isKnownString() && !isBoxed()) {
      return this;
    }
    if (BytecodeUtils.isPrimitive(resultType())) {
      if (resultType().equals(Type.BOOLEAN_TYPE)) {
        return forString(MethodRef.BOOLEAN_TO_STRING.invoke(delegate));
      } else if (resultType().equals(Type.DOUBLE_TYPE)) {
        return forString(MethodRef.DOUBLE_TO_STRING.invoke(delegate));
      } else if (resultType().equals(Type.LONG_TYPE)) {
        return forString(MethodRef.LONG_TO_STRING.invoke(delegate));
      } else {
        throw new AssertionError(
            "resultType(): " + resultType() + " is not a valid type for a SoyExpression");
      }
    }
    if (!isBoxed()) {
      // this is for unboxed reference types (strings, lists, protos) String.valueOf handles null
      // implicitly
      return forString(MethodRef.STRING_VALUE_OF.invoke(delegate));
    }
    return forString(MethodRef.RUNTIME_COERCE_TO_STRING.invoke(delegate));
  }
1332650
private boolean readLine() throws ParseException {
        try {
            return parser.Line();
        } catch (ParseException e) {
            yield();
            if ( EOF )
                return true;
            throw e;
        }
    }
1081578
final public void DeferredExpression() throws ParseException {
                                                 /*@bgen(jjtree) DeferredExpression */
  AstDeferredExpression jjtn000 = new AstDeferredExpression(JJTDEFERREDEXPRESSION);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(START_DEFERRED_EXPRESSION);
      Expression();
      jj_consume_token(RBRACE);
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000, true);
      }
    }
  }
1439
public Object evaluate(String expression) throws CompilationFailedException {
        GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding);
        return shell.evaluate(expression);
    }
643889
I parse(String text) throws ParseException {

        ParseLog plog = new ParseLog();
        AttributeQuery attrs = this.startFormat.getAttributes();
        I ret = this.parse(text, plog, attrs);
        int pos = plog.getPosition();
        int len = text.length();

        if ((ret == null) || plog.isError()) {
            throw new ParseException(
                plog.getErrorMessage(),
                plog.getErrorIndex());
        } else if (
            (pos < len)
            && !attrs.get(TRAILING_CHARACTERS, Boolean.FALSE).booleanValue()
        ) {
            String suffix;

            if (len - pos <= 10) {
                suffix = text.subSequence(pos, len).toString();
            } else {
                suffix = text.subSequence(pos, pos + 10).toString() + "...";
            }

            throw new ParseException("Unparsed trailing characters: " + suffix, pos);
        }

        return ret;

    }
1112474
final public Selector LikePredicate() throws ParseException {
                             Selector id; Token pat; Token esc=null; boolean neg=false;
    id = FieldRef();
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case NOT:
      jj_consume_token(NOT);
                              neg = true;
      break;
    default:
      jj_la1[17] = jj_gen;
      ;
    }
    jj_consume_token(LIKE);
    pat = jj_consume_token(STRING_LITERAL);
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case ESCAPE:
      jj_consume_token(ESCAPE);
      esc = jj_consume_token(STRING_LITERAL);
      break;
    default:
      jj_la1[18] = jj_gen;
      ;
    }
    Selector ans = ParseUtil.convertLike(id, pat.image, (esc==null) ? null : esc.image);
    if (ans == null) generateParseException();
    if (neg) {if (true) return new OperatorImpl(Operator.NOT, ans);}
    else {if (true) return ans;}
    throw new Error("Missing return statement in function");
  }
695095
private ExprKraken parseSelectExpr()
  {
    Token token = scanToken();

    if (token == Token.STAR) {
      // return new UnboundStarExpr();
      
      throw new UnsupportedOperationException(getClass().getName());
    }
    else {
      _token = token;

      return parseExpr();
    }
  }
362225
String parseString() throws IOException {
        buf.setLength(0);
        char next = readNext();
        while (next != '"') {
            if (next == '\\') {
                parseEscape();
            } else {
                buf.append(next);
            }
            next = readNext();
        }
        return buf.toString();
    }
184547
final public Selector NullPredicate() throws ParseException {
                             boolean not=false; Selector ans;
    ans = FieldRef();
    jj_consume_token(IS);
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case NOT:
      jj_consume_token(NOT);
                                    not = true;
      break;
    default:
      jj_la1[11] = jj_gen;
      ;
    }
    jj_consume_token(NULL);
    ans = new OperatorImpl(Operator.ISNULL, ans);
    if (not) {if (true) return new OperatorImpl(Operator.NOT, ans);}
    else {if (true) return ans;}
    throw new Error("Missing return statement in function");
  }
683259
private void evaluateExpressions() throws JspException {
        /* 
         * Note: we don't check for type mismatches here; we assume
         * the expression evaluator will return the expected type
         * (by virtue of knowledge we give it about what that type is).
         * A ClassCastException here is truly unexpected, so we let it
         * propagate up.
         */

        xml = ExpressionUtil.evalNotNull(
                "parse", "xml", xml_, Object.class, this, pageContext);
        systemId = (String) ExpressionUtil.evalNotNull(
                "parse", "systemId", systemId_, String.class, this, pageContext);

        try {
            filter = (XMLFilter) ExpressionUtil.evalNotNull(
                    "parse", "filter", filter_, XMLFilter.class, this, pageContext);
        } catch (NullAttributeException ex) {
            // explicitly let 'filter' be null
            filter = null;
        }
    }
1109772
public static Evaluator parse(String query) {
        try {
            QueryParser p = new QueryParser(query);
            return p.parse();
        } catch (IllegalArgumentException e) {
            throw new Selector.SelectorParseException(e.getMessage());
        }
    }
448356
public Result parse() throws IOException {
		List<Term> list = new ArrayList<Term>();
		Term temp = null;
		while ((temp = next()) != null) {
			list.add(temp);
		}
		Result result = new Result(list);
		return result;
	}