Exemplo n.º 1
0
  /** Evaluate isUnique expression. */
  protected final Value evalIsUnique(EvalContext ctx) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // collect values for finding duplicates
    Set<Value> values = new HashSet<Value>();

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate collect expression
      Value val = fQueryExp.eval(ctx);

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();

      // stop if duplicate element is found
      if (values.contains(val)) return BooleanValue.FALSE;
      else values.add(val);
    }

    // result is true if no duplicates where found
    return BooleanValue.TRUE;
  }
Exemplo n.º 2
0
  /** Evaluate collect expressions. */
  protected final Value evalCollectNested(EvalContext ctx) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // prepare result value
    ArrayList<Value> resValues = new ArrayList<Value>();

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate collect expression
      Value val = fQueryExp.eval(ctx);

      // add element to result
      resValues.add(val);

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();
    }

    // result is collection with mapped values
    if (fRangeExp.type().isSequence() || fRangeExp.type().isOrderedSet())
      return new SequenceValue(fQueryExp.type(), resValues);
    else return new BagValue(fQueryExp.type(), resValues);
  }
Exemplo n.º 3
0
 public PacioliValue eval(Environment env) throws IOException {
   Boole outcome = (Boole) lhs.eval(env);
   if (!outcome.positive()) {
     return rhs.eval(env);
   } else {
     return outcome;
   }
 }
Exemplo n.º 4
0
 public StoreAndValue eval(Store s, Environment e) {
   StoreAndValue s_and_v = condition.eval(s, e);
   BoolValue cond = (BoolValue) s_and_v.value;
   if (cond.value) {
     return thenPart.eval(s_and_v.store, e);
   } else {
     return elsePart.eval(s_and_v.store, e);
   }
 }
Exemplo n.º 5
0
  /**
   * Verify that operations chained together are implicitly performing composition; this is a really
   * important aspect of the architecture so it is imperative that the program does this properly.
   *
   * <p>Verify that the evaluation of an expression changes when the values of its variables change.
   */
  @Test
  public void testEvalSampleExpression() {
    Variable x = new Variable("x");
    Variable y = new Variable("y");

    Evaluable root = new Addition(new Multiplication(new Negation(new Constant(3)), x), y);

    Expression expr = new Expression(root, Arrays.asList(x, y));
    assertEquals(BigDecimal.valueOf(-2), expr.eval(BigDecimal.ONE, BigDecimal.ONE));
    assertEquals(BigDecimal.valueOf(-3), expr.eval(BigDecimal.ONE, BigDecimal.ZERO));
    assertEquals(BigDecimal.valueOf(+1), expr.eval(BigDecimal.ZERO, BigDecimal.ONE));
  }
  @Override
  public int eval(IDictionary symbols) throws ToyExecutionException {

    int result1 = exp1.eval(symbols);
    int result2 = exp2.eval(symbols);
    switch (operator) {
      case "+":
        return result1 + result2;
      case "-":
        return result1 - result2;
      case "*":
        return result1 * result2;
    }
    return 0;
  }
Exemplo n.º 7
0
  @Override
  public Object eval(LogMap map) {
    Object v = expr.eval(map);
    if (v == null) return false;

    return v instanceof Number;
  }
Exemplo n.º 8
0
  /* (non-Javadoc)
   * @see org.exist.xquery.Expression#eval(org.exist.xquery.StaticContext, org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
   */
  public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
      context.getProfiler().start(this);
      context
          .getProfiler()
          .message(
              this,
              Profiler.DEPENDENCIES,
              "DEPENDENCIES",
              Dependency.getDependenciesName(this.getDependencies()));
      if (contextSequence != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
      if (contextItem != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
    }

    Sequence result = atomize(expression.eval(contextSequence, contextItem));

    if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result);

    return result;
  }
Exemplo n.º 9
0
 public XQValue eval(Focus focus, EvalContext context) throws EvaluationException {
   context.at(this);
   while (cond.evalEffectiveBooleanValue(focus, context)) {
     block.eval(focus, context);
   }
   return XQValue.empty;
 }
 public Object eval(Map<String, Object> env) throws SQLException {
   Integer retval;
   Object o = env.get(GROUPING_COLUMN_NAME);
   if (o != null) {
     /*
      * The count is the number of rows grouped together
      * by the GROUP BY clause.
      */
     List groupRows = (List) o;
     if (this.distinctValues != null) {
       HashSet<Object> unique = new HashSet<Object>();
       for (int i = 0; i < groupRows.size(); i++) {
         o = expression.eval((Map) groupRows.get(i));
         if (o != null) {
           unique.add(o);
         }
       }
       retval = Integer.valueOf(unique.size());
     } else {
       retval = Integer.valueOf(groupRows.size());
     }
   } else {
     if (this.distinctValues != null) {
       retval = Integer.valueOf(this.distinctValues.size());
     } else {
       retval = Integer.valueOf(counter);
     }
   }
   return retval;
 }
Exemplo n.º 11
0
  @Test
  public void testEval() throws ParseException {

    int n = 0;

    Object[][] tests = {
      {"1.0", 1.0},
      {"a = 2.0; a", 2.0},
      {"a = 2.0; b = a + 1; return b", 3.0},
    };

    for (Object[] test : tests) {

      n++;

      CurtaNode ast = new CurtaParser(new java.io.StringReader((String) test[0])).ast();

      assertThat(ast.treeType, is(type));
      assertThat(ast.jjtGetNumChildren(), is(n));

      Object value = expression.eval(ast, super.variables, super.functions, super.expressions);

      assertEquals(value, test[1]);
    }
  }
Exemplo n.º 12
0
  @Test
  public void testMathContext() {
    Expression e = null;
    e = new Expression("2.5/3").setPrecision(2);
    assertEquals("0.83", e.eval().toPlainString());

    e = new Expression("2.5/3").setPrecision(3);
    assertEquals("0.833", e.eval().toPlainString());

    e = new Expression("2.5/3").setPrecision(8);
    assertEquals("0.83333333", e.eval().toPlainString());

    e = new Expression("2.5/3").setRoundingMode(RoundingMode.DOWN);
    assertEquals("0.8333333", e.eval().toPlainString());

    e = new Expression("2.5/3").setRoundingMode(RoundingMode.UP);
    assertEquals("0.8333334", e.eval().toPlainString());
  }
Exemplo n.º 13
0
  /** Evaluate sortedBy expressions. */
  protected final Value evalSortedBy(EvalContext ctx) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    ArrayList<KeyValPair> keyValList = new ArrayList<KeyValPair>();

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate sortedBy expression and store the result as a
      // key together with elemVal
      Value key = fQueryExp.eval(ctx);
      keyValList.add(new KeyValPair(key, elemVal));

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();
    }

    // sort elements by key
    Collections.sort(
        keyValList,
        new Comparator<KeyValPair>() {
          public int compare(KeyValPair o1, KeyValPair o2) {
            return o1.fKey.compareTo(o2.fKey);
          }
        });

    // drop the keys from the list
    ListIterator<KeyValPair> listIter = keyValList.listIterator();
    Collection<Value> result = new ArrayList<Value>(keyValList.size());

    while (listIter.hasNext()) {
      KeyValPair kvp = listIter.next();
      result.add(kvp.fElem);
    }

    Type rangeElemType = ((CollectionType) fRangeExp.type()).elemType();
    return new SequenceValue(rangeElemType, result);
  }
Exemplo n.º 14
0
  /** Evaluate select and reject expressions. */
  protected final Value evalSelectOrReject(EvalContext ctx, boolean doSelect) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // prepare result value
    ArrayList<Value> resValues = new ArrayList<Value>();
    Type elemType = rangeVal.elemType();
    if (!rangeVal.type().isInstantiableCollection())
      throw new RuntimeException("rangeVal is not of collection type: " + rangeVal.type());

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate select expression
      Value queryVal = fQueryExp.eval(ctx);

      // undefined query values default to false
      if (queryVal.isUndefined()) queryVal = BooleanValue.FALSE;

      if (((BooleanValue) queryVal).value() == doSelect) resValues.add(elemVal);

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();
    }

    CollectionValue res;
    if (rangeVal.type().isSet()) res = new SetValue(elemType, resValues);
    else if (rangeVal.type().isSequence()) res = new SequenceValue(elemType, resValues);
    else if (rangeVal.type().isBag()) res = new BagValue(elemType, resValues);
    else if (rangeVal.type().isOrderedSet()) res = new OrderedSetValue(elemType, resValues);
    else {
      // should not happen
      throw new RuntimeException("rangeVal is not of collection type: " + rangeVal.type());
    }
    // result is collection with selected/rejected values
    return res;
  }
Exemplo n.º 15
0
 @Test
 public void testWrongBrackets2() {
   String err = "";
   try {
     Expression expression = new Expression("2*(3((5*3)))");
     expression.eval();
   } catch (ExpressionException e) {
     err = e.getMessage();
   }
   assertEquals("Missing operator at character position 5", err);
 }
Exemplo n.º 16
0
  /**
   * Evaluate exists and forAll expressions. The array <code>moreElemVars</code> may be null if
   * there is at most one element variable declared.
   */
  protected final Value evalExistsOrForAll(EvalContext ctx, boolean doExists) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // we need recursion for the permutation of assignments of
    // range values to all element variables.
    boolean res = evalExistsOrForAll0(0, rangeVal, ctx, doExists);
    return BooleanValue.get(res);
  }
Exemplo n.º 17
0
  public XQValue eval(Focus focus, EvalContext context) throws EvaluationException {
    context.at(this);
    try {
      XQValue res = caught.eval(focus, context);
      // it is crucial to expand the sequence here, so that
      // eval errors are actually caught
      ArraySequence expanded = new ArraySequence(4, res);
      for (; res.next(); ) expanded.addItem(res.getItem());
      return expanded;
    } catch (EvaluationException e) {
      Catch catcher = null;
      for (int i = 0; i < catches.length; i++) {
        if (catches[i].catches(e.getErrorCode())) {
          catcher = catches[i];
          break;
        }
      }

      if (catcher == null) throw e;
      if (compatibility) {
        // feature: show error as a node whose name is the error code
        // and whose content the message
        CorePushBuilder builder = new CorePushBuilder("");
        QName errName = IQName.get(e.getErrorCode());
        try {
          builder.putElementStart(errName); // cant be attr value
          builder.putText(e.getMessage());
          builder.putElementEnd(errName);
        } catch (QizxException e1) {;
        }
        context.storeLocal(
            catcher.valueVar.address, new SingleNode(builder.harvest()), false /* current */, null);
      } else { // 1.1
        if (catcher.codeVar != null) {
          context.storeLocal(
              catcher.codeVar.address,
              new SingleQName(e.getErrorCode()),
              false /* current */,
              null);
        }
        if (catcher.descVar != null) {
          context.storeLocal(
              catcher.descVar.address, new SingleString(e.getMessage()), false /* current */, null);
        }
        if (catcher.valueVar != null) {
          XQValue v = e.getValue();
          if (v == null) v = XQValue.empty;
          context.storeLocal(catcher.valueVar.address, v, false /* current */, null);
        }
      }
      // execute the handler with bound variables (if any)
      return catcher.handler.eval(focus, context);
    }
  }
 @Override
 TemplateModel _eval(Environment env) throws TemplateException {
   TemplateNumberModel targetModel = null;
   TemplateModel tm = target.eval(env);
   try {
     targetModel = (TemplateNumberModel) tm;
   } catch (ClassCastException cce) {
     throw new NonNumericalException(target, tm, env);
   }
   if (!isMinus) {
     return targetModel;
   }
   target.assertNonNull(targetModel, env);
   Number n = targetModel.getAsNumber();
   n = ArithmeticEngine.CONSERVATIVE_ENGINE.multiply(MINUS_ONE, n);
   return new SimpleNumber(n);
 }
 Context(Environment env) throws TemplateException {
   invokingMacroContext = env.getCurrentMacroContext();
   List bodyParameterNames = invokingMacroContext.nestedContentParameterNames;
   if (bodyParameters != null) {
     for (int i = 0; i < bodyParameters.size(); i++) {
       Expression exp = (Expression) bodyParameters.get(i);
       TemplateModel tm = exp.eval(env);
       if (bodyParameterNames != null && i < bodyParameterNames.size()) {
         String bodyParameterName = (String) bodyParameterNames.get(i);
         if (bodyVars == null) {
           bodyVars = env.new Namespace();
         }
         bodyVars.put(bodyParameterName, tm);
       }
     }
   }
 }
Exemplo n.º 20
0
 public static void main(String[] args) throws Exception {
   // creates the expression tree corresponding to
   //   exp(i) = i > 3 && 6 > i
   Exp exp = new And(new GT(new Var(0), new Cst(3)), new GT(new Cst(6), new Var(0)));
   // compiles this expression into an Expression class
   Compile main = new Compile();
   byte[] b = exp.compile("Example");
   FileOutputStream fos = new FileOutputStream("Example.class");
   fos.write(b);
   fos.close();
   Class expClass = main.defineClass("Example", b, 0, b.length);
   // instantiates this compiled expression class...
   Expression iexp = (Expression) expClass.newInstance();
   // ... and uses it to evaluate exp(0) to exp(9)
   for (int i = 0; i < 10; ++i) {
     boolean val = iexp.eval(i, 0) == 1;
     System.out.println(i + " > 3 && " + i + " < 6 = " + val);
   }
 }
 public void processRow(Map<String, Object> env) throws SQLException {
   if (expression instanceof AsteriskExpression) {
     counter++;
   } else {
     /*
      * Only count non-null values.
      */
     Object o = expression.eval(env);
     if (o != null) {
       counter++;
       if (distinctValues != null) {
         /*
          * We want a count of DISTINCT values, so we have
          * to keep a list of unique values.
          */
         distinctValues.add(o);
       }
     }
   }
 }
Exemplo n.º 22
0
  @Override
  void exec(Environment env) throws EvalException, InterruptedException {
    List<Expression> defaultExpressions = signature.getDefaultValues();
    ArrayList<Object> defaultValues = null;
    ArrayList<SkylarkType> types = null;

    if (defaultExpressions != null) {
      defaultValues = new ArrayList<>(defaultExpressions.size());
      for (Expression expr : defaultExpressions) {
        defaultValues.add(expr.eval(env));
      }
    }
    env.update(
        ident.getName(),
        new UserDefinedFunction(
            ident,
            FunctionSignature.WithValues.<Object, SkylarkType>create(
                signature.getSignature(), defaultValues, types),
            statements,
            (SkylarkEnvironment) env));
  }
Exemplo n.º 23
0
  private final boolean evalExistsOrForAll0(
      int nesting, CollectionValue rangeVal, EvalContext ctx, boolean doExists) {
    // loop over range elements
    boolean res = !doExists;

    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty())
        ctx.pushVarBinding(fElemVarDecls.varDecl(nesting).name(), elemVal);

      if (!fElemVarDecls.isEmpty() && nesting < fElemVarDecls.size() - 1) {
        // call recursively to iterate over range while
        // assigning each value to each element variable
        // eventually
        if (res != doExists) res = evalExistsOrForAll0(nesting + 1, rangeVal, ctx, doExists);
        else
          // don't change the result value when expression is true
          // (exists) or
          // false (forAll) and continue iteration
          evalExistsOrForAll0(nesting + 1, rangeVal, ctx, doExists);
      } else {
        // evaluate predicate expression
        Value queryVal = fQueryExp.eval(ctx);

        // undefined query values default to false
        if (queryVal.isUndefined()) queryVal = BooleanValue.FALSE;

        // don't change the result value when expression is true
        // (exists) or
        // false (forAll) and continue iteration
        if (res != doExists && ((BooleanValue) queryVal).value() == doExists) res = doExists;
      }

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();
    }

    return res;
  }
Exemplo n.º 24
0
  @Override
  public Object eval(Environment e) {
    Object param = this.exprs.get(0).eval(e);
    if (param instanceof ExpressionExpression) {
      ExpressionExpression exp = (ExpressionExpression) param;
      Object result = null;
      for (int i = 0; i < exp.exprs.size(); i++) {
        result = exp.exprs.get(i).eval(e);
      }
      return (result);
    } else if (param instanceof String) {
      Parser parser = new Parser(param.toString());
      Expression exp = null;
      Object result = null;
      while (true) {

        try {
          exp = parser.getNextExpression();
        } catch (Exception exc) {
          break;
        }

        if (exp == null) {
          break;
        }

        try {
          result = exp.eval(e);
        } catch (Exception exc) {
          System.out.println("eval: Runtime Error: " + exc.toString());
          exc.printStackTrace();
          System.exit(-1);
        }
      }
      return (result);
    }
    return (null);
  }
Exemplo n.º 25
0
  /* (non-Javadoc)
   * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
   */
  public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
      context.getProfiler().start(this);
      context
          .getProfiler()
          .message(
              this,
              Profiler.DEPENDENCIES,
              "DEPENDENCIES",
              Dependency.getDependenciesName(this.getDependencies()));
      if (contextSequence != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
      if (contextItem != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
    }

    if (contextItem != null) contextSequence = contextItem.toSequence();

    Sequence result;
    Sequence seq = expression.eval(contextSequence, contextItem);
    if (seq.isEmpty()) result = Sequence.EMPTY_SEQUENCE;
    else {
      //    		seq.setSelfAsContext();
      result = seq;
      for (Iterator i = predicates.iterator(); i.hasNext(); ) {
        Predicate pred = (Predicate) i.next();
        result = pred.evalPredicate(contextSequence, result, Constants.DESCENDANT_SELF_AXIS);
      }
    }

    if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result);

    return result;
  }
Exemplo n.º 26
0
  /*
   * (non-Javadoc)
   *
   * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[],
   *      org.exist.xquery.value.Sequence)
   */
  public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {

    if (context.getProfiler().isEnabled()) {
      context.getProfiler().start(this);
      context
          .getProfiler()
          .message(
              this,
              Profiler.DEPENDENCIES,
              "DEPENDENCIES",
              Dependency.getDependenciesName(this.getDependencies()));
      if (contextSequence != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
      if (contextItem != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
    }

    Expression arg1 = getArgument(0);
    Sequence s1 = arg1.eval(contextSequence, contextItem);

    Expression arg2 = getArgument(1);
    context.pushDocumentContext();
    Sequence s2 = arg2.eval(contextSequence, contextItem);
    context.popDocumentContext();

    if (s1.isEmpty()) {
      return BooleanValue.valueOf(s2.isEmpty());
    } else if (s2.isEmpty()) {
      return BooleanValue.valueOf(s1.isEmpty());
    }

    Sequence result = null;
    StringBuffer v1 = new StringBuffer();
    StringBuffer v2 = new StringBuffer();
    try {
      if (s1.hasMany()) {
        for (int i = 0; i < s1.getItemCount(); i++) {
          v1.append(serialize((NodeValue) s1.itemAt(i)));
        }
      } else {
        v1.append(serialize((NodeValue) s1.itemAt(0)));
      }
      if (s2.hasMany()) {
        for (int i = 0; i < s2.getItemCount(); i++) {
          v2.append(serialize((NodeValue) s2.itemAt(i)));
        }
      } else {
        v2.append(serialize((NodeValue) s2.itemAt(0)));
      }
      Diff d = new Diff(v1.toString(), v2.toString());
      boolean identical = d.identical();
      if (!identical) {
        logger.warn("Diff result: " + d.toString());
      }
      result = new BooleanValue(identical);
    } catch (Exception e) {
      throw new XPathException(
          this,
          "An exception occurred while serializing node " + "for comparison: " + e.getMessage(),
          e);
    }

    if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result);

    return result;
  }
Exemplo n.º 27
0
  /* (non-Javadoc)
   * @see org.exist.xquery.AbstractExpression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
   */
  public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
      context.getProfiler().start(this);
      context
          .getProfiler()
          .message(
              this,
              Profiler.DEPENDENCIES,
              "DEPENDENCIES",
              Dependency.getDependenciesName(this.getDependencies()));
      if (contextSequence != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
      if (contextItem != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
    }

    if (requiredType == Type.ATOMIC
        || (requiredType == Type.NOTATION && expression.returnsType() != Type.NOTATION))
      throw new XPathException(
          this, "err:XPST0080: cannot convert to " + Type.getTypeName(requiredType));

    if (requiredType == Type.ANY_SIMPLE_TYPE
        || expression.returnsType() == Type.ANY_SIMPLE_TYPE
        || requiredType == Type.UNTYPED
        || expression.returnsType() == Type.UNTYPED)
      throw new XPathException(
          this, "err:XPST0051: cannot convert to " + Type.getTypeName(requiredType));

    Sequence result;
    // See : http://article.gmane.org/gmane.text.xml.xquery.general/1413
    // ... for the rationale
    // may be more complicated : let's see with following XQTS versions
    if (requiredType == Type.QNAME && Dependency.dependsOnVar(expression))
      result = BooleanValue.FALSE;
    else {
      Sequence seq = expression.eval(contextSequence, contextItem);
      if (seq.isEmpty()) {
        // If ? is specified after the target type, the result of the cast expression is an empty
        // sequence.
        if (Cardinality.checkCardinality(requiredCardinality, Cardinality.ZERO))
          result = BooleanValue.TRUE;
        // If ? is not specified after the target type, a type error is raised [err:XPTY0004].
        else
          // TODO : raise the error ?
          result = BooleanValue.FALSE;
      } else {
        try {
          seq.itemAt(0).convertTo(requiredType);
          // If ? is specified after the target type, the result of the cast expression is an empty
          // sequence.
          if (Cardinality.checkCardinality(requiredCardinality, seq.getCardinality()))
            result = BooleanValue.TRUE;
          // If ? is not specified after the target type, a type error is raised [err:XPTY0004].
          else result = BooleanValue.FALSE;
          // TODO : improve by *not* using a costly exception ?
        } catch (XPathException e) {
          result = BooleanValue.FALSE;
        }
      }
    }

    if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result);

    return result;
  }
Exemplo n.º 28
0
  @Override
  public Value eval(Context ctxt) {
    // No break check here, as we want to stop in the expression

    // The postcondition function arguments are the function args, the
    // result, the old/new state (if any). These all exist in ctxt.
    // We find the Sigma record and expand its contents to give additional
    // values in ctxt for each field. Ditto with Sigma~.

    try {
      if (state != null) {
        RecordValue sigma = ctxt.lookup(state.name).recordValue(ctxt);

        for (Field field : state.fields) {
          ctxt.put(field.tagname, sigma.fieldmap.get(field.tag));
        }

        RecordValue oldsigma = ctxt.lookup(state.name.getOldName()).recordValue(ctxt);

        for (Field field : state.fields) {
          ctxt.put(field.tagname.getOldName(), oldsigma.fieldmap.get(field.tag));
        }
      } else if (ctxt instanceof ObjectContext) {
        ObjectContext octxt = (ObjectContext) ctxt;
        LexNameToken selfname = opname.getSelfName();
        LexNameToken oldselfname = selfname.getOldName();

        ObjectValue self = octxt.lookup(selfname).objectValue(ctxt);
        ValueMap oldvalues = octxt.lookup(oldselfname).mapValue(ctxt);

        // If the opname was defined in a superclass of "self", we have
        // to discover the subobject to populate its state variables.

        ObjectValue subself = findObject(opname.module, self);

        if (subself == null) {
          abort(4026, "Cannot create post_op environment", ctxt);
        }

        // Create an object context using the "self" passed in, rather
        // than the self that we're being called from, assuming they
        // are different.

        if (subself != octxt.self) {
          ObjectContext selfctxt =
              new ObjectContext(ctxt.location, "postcondition's object", ctxt, subself);

          selfctxt.putAll(ctxt); // To add "RESULT" and args.
          ctxt = selfctxt;
        }

        populate(ctxt, subself.type.name.name, oldvalues); // To add old "~" values
      } else if (ctxt instanceof ClassContext) {
        LexNameToken selfname = opname.getSelfName();
        LexNameToken oldselfname = selfname.getOldName();
        ValueMap oldvalues = ctxt.lookup(oldselfname).mapValue(ctxt);
        populate(ctxt, opname.module, oldvalues);
      }

      // If there are errs clauses, and there is a precondition defined, then
      // we evaluate that as well as the postcondition.

      boolean result =
          (errors == null || preexpression == null || preexpression.eval(ctxt).boolValue(ctxt))
              && postexpression.eval(ctxt).boolValue(ctxt);

      errorLocation = location;

      if (errors != null) {
        for (ErrorCase err : errors) {
          boolean left = err.left.eval(ctxt).boolValue(ctxt);
          boolean right = err.right.eval(ctxt).boolValue(ctxt);

          if (left && !right) {
            errorLocation = err.left.location;
          }

          result = result || (left && right);
        }
      }

      return new BooleanValue(result);
    } catch (ValueException e) {
      return abort(e);
    }
  }
Exemplo n.º 29
0
 @Override
 public int binOp(Expression x, Expression y) {
   return x.eval() + y.eval();
 }
Exemplo n.º 30
0
 public double eval() {
   return op1.eval() - op2.eval();
 }