Exemple #1
0
 public Expression eliminateLet() {
   Vector<Expression> new_operands = new Vector<Expression>();
   for (Expression o : operands) {
     new_operands.add(o.eliminateLet());
   }
   return new Application(operator.eliminateLet(), new_operands);
 }
  @Override
  public Expression<K> applyInternal(And<K> input) {

    for (Expression<K> expr : input.expressions) {
      if (expr instanceof Literal) {
        Literal l = (Literal) expr;

        if (l.getValue()) {
          return copyWithoutTrue(input);
        } else {
          return Literal.getFalse();
        }
      }

      //  succeed immediately if require something or its opposite
      if (expr instanceof Not) {
        Expression<K> notChild = ((Not<K>) expr).getE();
        for (Expression<K> child : input.expressions) {
          if (child.equals(notChild)) {
            return Literal.getFalse();
          }
        }
      }
    }

    return input;
  }
Exemple #3
0
 // Constructs a simple expression from the given Cetus expression
 protected SimpleExpression(Expression e) {
   this();
   if (e instanceof UnaryExpression) parse((UnaryExpression) e);
   else if (e instanceof BinaryExpression) parse((BinaryExpression) e);
   else if (e.getChildren() != null && !e.getChildren().isEmpty()) parseTree(e);
   else parseLeaf(e);
 }
Exemple #4
0
  /** @see jaskell.compiler.JaskellVisitor#visit(QualifiedVariable) */
  public Object visit(QualifiedVariable a) {
    Module mod = null;
    Iterator it = a.getPath().iterator();
    while (it.hasNext()) {
      String mname = (String) it.next();
      if (mod != null) mod = (Module) mod.lookup(mname);
      else mod = (Module) Module.getToplevels().get(mname);
    }
    /* module found */
    if (mod != null) {
      Expression def = mod.lookup(a.getName());
      if (def == null) throw new CompilerException("Unknown variable " + a.getName());
      Type t = def.getType();
      if (t == null) t = (Type) def.visit(this);

      /* as it is the case for variable, we assume
       * that a defined symbol may be overloaded (only for primitive types)
       * so we return a type variable and defers choice of
       * symbol to a later stage
       */
      a.setType(t);
      return t;
    }
    throw new CompilerException("Unable to find module needed for variable " + a.getName());
  }
  /** 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;
  }
  protected Query range(
      Path<?> leftHandSide,
      String field,
      @Nullable Expression<?> min,
      @Nullable Expression<?> max,
      boolean minInc,
      boolean maxInc,
      QueryMetadata metadata) {
    if (min != null && Number.class.isAssignableFrom(min.getType())
        || max != null && Number.class.isAssignableFrom(max.getType())) {
      @SuppressWarnings("unchecked") // guarded by previous check
      Constant<? extends Number> minConstant = (Constant<? extends Number>) min;
      @SuppressWarnings("unchecked") // guarded by previous check
      Constant<? extends Number> maxConstant = (Constant<? extends Number>) max;

      Class<? extends Number> numType =
          minConstant != null ? minConstant.getType() : maxConstant.getType();
      // this is not necessarily safe, but compile time checking
      // on the user side mandates these types to be interchangeable
      @SuppressWarnings("unchecked")
      Class<Number> unboundedNumType = (Class<Number>) numType;
      return numericRange(
          unboundedNumType,
          field,
          minConstant == null ? null : minConstant.getConstant(),
          maxConstant == null ? null : maxConstant.getConstant(),
          minInc,
          maxInc);
    }
    return stringRange(leftHandSide, field, min, max, minInc, maxInc, metadata);
  }
Exemple #7
0
  /**
   * The constructor is protected, to ensure that instances can only be created using the
   * compileQuery() methods of StaticQueryContext
   *
   * @param exp an expression to be wrapped as an XQueryExpression
   * @param exec the executable
   * @param mainModule the static context of the main module
   * @param config the configuration
   * @throws XPathException if an error occurs
   */
  protected XQueryExpression(
      Expression exp, Executable exec, QueryModule mainModule, Configuration config)
      throws XPathException {
    stackFrameMap = config.makeSlotManager();
    executable = exec;
    exp.setContainer(this);
    try {
      ExpressionVisitor visitor = ExpressionVisitor.make(mainModule);
      visitor.setExecutable(exec);
      exp = visitor.simplify(exp);
      exp.checkForUpdatingSubexpressions();
      exp = visitor.typeCheck(exp, mainModule.getUserQueryContext().getRequiredContextItemType());
      //            ExpressionPresenter presenter = new ExpressionPresenter(config,
      //                    ExpressionPresenter.defaultDestination(config, new
      // FileOutputStream("c:/projects/montreal/before50.xml")));
      //            exp.explain(presenter);
      //            presenter.close();
      exp = exp.optimize(visitor, Type.ITEM_TYPE);
    } catch (XPathException err) {
      // err.printStackTrace();
      mainModule.reportFatalError(err);
      throw err;
    }
    ExpressionTool.allocateSlots(exp, 0, stackFrameMap);

    expression = exp;
    executable.setConfiguration(config);
    executable.setDefaultCollationName(mainModule.getDefaultCollationName());
    executable.setCollationTable(mainModule.getUserQueryContext().getAllCollations());
    staticContext = mainModule;
    isUpdating = exp.isUpdatingExpression();
  }
 @Override
 public void visit(ExpressionList el) {
   for (Iterator iter = el.getExpressions().iterator(); iter.hasNext(); ) {
     Expression expression = (Expression) iter.next();
     expression.accept(this);
   }
 }
  /*
   * INTERNAL:
   * If this query key represents a foreign reference answer the
   * base expression -> foreign reference join criteria.
   */
  public Expression mappingCriteria() {
    Expression selectionCriteria;

    // First look for a query key, then a mapping
    if (getQueryKeyOrNull() == null) {
      if ((getMapping() == null) || (!getMapping().isForeignReferenceMapping())) {
        return null;
      } else {
        // The join criteria is now twisted by the mappings.
        selectionCriteria = ((ForeignReferenceMapping) getMapping()).getJoinCriteria(this);
      }
    } else {
      if (!getQueryKeyOrNull().isForeignReferenceQueryKey()) {
        return null;
      } else {
        selectionCriteria = ((ForeignReferenceQueryKey) getQueryKeyOrNull()).getJoinCriteria();
        selectionCriteria = getBaseExpression().twist(selectionCriteria, this);
      }
    }

    if (shouldUseOuterJoin() && getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) {
      selectionCriteria = selectionCriteria.convertToUseOuterJoin();
    }

    return selectionCriteria;
  }
Exemple #10
0
 /*
  * (non-Javadoc)
  *
  * @see jaskell.compiler.JaskellVisitor#visit(jaskell.compiler.core.Module)
  */
 public Object visit(Namespace a) {
   /* set current namespace */
   ns = a;
   /*
    * visit definitions We set an infinite loop to cope with modifications
    * introduced by visiting sub expressions. When something is modified -
    * through lift - we restart the whole process. TODO : change this to defer
    * registering new bindings at end
    */
   while (true) {
     try {
       Iterator it = a.getAllBindings().entrySet().iterator();
       while (it.hasNext()) {
         Map.Entry entry = (Map.Entry) it.next();
         String functionName = (String) entry.getKey();
         Expression def = (Expression) entry.getValue();
         if (def instanceof Abstraction)
           ((Abstraction) def).setClassName(ns.getName() + "." + functionName);
         log.finest("Analyzing lifting for " + functionName);
         lift = false;
         entry.setValue((Expression) def.visit(this));
       }
       break;
     } catch (ConcurrentModificationException cmex) {
       /* restart the process */
     }
   }
   return a;
 }
Exemple #11
0
 /*
  * If we visit a nested abstraction, we just launch a new lift operation on
  * this abstraction using current context as namespace and returns an
  * Application object
  *
  * @see jaskell.compiler.JaskellVisitor#visit(jaskell.compiler.core.Abstraction)
  */
 public Object visit(Abstraction a) {
   if (!lift) {
       /* top level abstractions */
     lift = true;
     a.setBody((Expression) a.getBody().visit(this));
     return a;
   }
   /* first visit body */
   a.setBody((Expression) a.getBody().visit(this));
   /* retrieve outer LocalBindings */
   Set captured = new HashSet();
   CaptureCollector cc = new CaptureCollector(captured);
   a.visit(cc);
   /* return the newly computed abstraction as an application spine */
   String vname;
   try {
     vname = lift(a, captured);
     Expression ex = applyLifted(vname, captured);
     ex.setParent(a.getParent());
     return ex;
   } catch (SymbolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return null;
   }
 }
  private void writeMapDotProperty(
      final Expression receiver,
      final String methodName,
      final MethodVisitor mv,
      final boolean safe) {
    receiver.visit(controller.getAcg()); // load receiver

    Label exit = new Label();
    if (safe) {
      Label doGet = new Label();
      mv.visitJumpInsn(IFNONNULL, doGet);
      controller.getOperandStack().remove(1);
      mv.visitInsn(ACONST_NULL);
      mv.visitJumpInsn(GOTO, exit);
      mv.visitLabel(doGet);
      receiver.visit(controller.getAcg());
    }

    mv.visitLdcInsn(methodName); // load property name
    mv.visitMethodInsn(
        INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
    if (safe) {
      mv.visitLabel(exit);
    }
    controller.getOperandStack().replace(OBJECT_TYPE);
  }
 @Override
 public void makeSingleArgumentCall(
     final Expression receiver, final String message, final Expression arguments) {
   TypeChooser typeChooser = controller.getTypeChooser();
   ClassNode classNode = controller.getClassNode();
   ClassNode rType = typeChooser.resolveType(receiver, classNode);
   ClassNode aType = typeChooser.resolveType(arguments, classNode);
   if (trySubscript(receiver, message, arguments, rType, aType)) {
     return;
   }
   // new try with flow type instead of declaration type
   rType = receiver.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
   if (rType != null && trySubscript(receiver, message, arguments, rType, aType)) {
     return;
   }
   // todo: more cases
   throw new GroovyBugError(
       "At line "
           + receiver.getLineNumber()
           + " column "
           + receiver.getColumnNumber()
           + "\n"
           + "On receiver: "
           + receiver.getText()
           + " with message: "
           + message
           + " and arguments: "
           + arguments.getText()
           + "\n"
           + "This method should not have been called. Please try to create a simple example reproducing this error and file"
           + "a bug report at http://jira.codehaus.org/browse/GROOVY");
 }
  protected Expression transformPropertyExpression(PropertyExpression pe) {
    boolean oldInPropertyExpression = inPropertyExpression;
    Expression oldFoundArgs = foundArgs;
    Expression oldFoundConstant = foundConstant;
    inPropertyExpression = true;
    foundArgs = null;
    foundConstant = null;
    Expression objectExpression = transform(pe.getObjectExpression());
    boolean candidate = false;
    if (objectExpression instanceof MethodCallExpression) {
      candidate = ((MethodCallExpression) objectExpression).isImplicitThis();
    }

    if (foundArgs != null && foundConstant != null && candidate) {
      Expression result = findStaticMethodImportFromModule(foundConstant, foundArgs);
      if (result != null) {
        objectExpression = result;
        objectExpression.setSourcePosition(pe);
      }
    }
    inPropertyExpression = oldInPropertyExpression;
    foundArgs = oldFoundArgs;
    foundConstant = oldFoundConstant;
    pe.setObjectExpression(objectExpression);
    return pe;
  }
  private Expression transformInlineConstants(Expression exp) {
    if (exp instanceof PropertyExpression) {
      PropertyExpression pe = (PropertyExpression) exp;
      if (pe.getObjectExpression() instanceof ClassExpression) {
        ClassExpression ce = (ClassExpression) pe.getObjectExpression();
        ClassNode type = ce.getType();
        if (type.isEnum()) return exp;
        Expression constant = findConstant(type.getField(pe.getPropertyAsString()));
        // GRECLIPSE edit
        // if (constant != null) return constant;
        if (constant != null) {
          String name = pe.getText().replace('$', '.');
          Object alias = pe.getNodeMetaData("static.import.alias");
          if (alias != null && !alias.equals(pe.getPropertyAsString())) {
            name += " as " + alias;
          }
          // store the qualified name to facilitate organizing static imports
          constant.setNodeMetaData("static.import", name);

          return constant;
        }
        // GRECLIPSE end
      }
    } else if (exp instanceof ListExpression) {
      ListExpression le = (ListExpression) exp;
      ListExpression result = new ListExpression();
      for (Expression e : le.getExpressions()) {
        result.addExpression(transformInlineConstants(e));
      }
      return result;
    }

    return exp;
  }
Exemple #16
0
  protected ExpQuery(
      Type resultType, VarDeclList elemVarDecls, Expression rangeExp, Expression queryExp)
      throws ExpInvalidException {
    super(resultType, rangeExp, queryExp);
    fElemVarDecls = elemVarDecls;
    fRangeExp = rangeExp;
    fQueryExp = queryExp;

    // type of rangeExp must be a subtype of Collection, i.e. Set,
    // Sequence or Bag
    if (!fRangeExp.type().isCollection(false))
      throw new ExpInvalidException(
          "Range expression must be of type " + "`Collection', found `" + fRangeExp.type() + "'.");

    // assert that declard element variables are equal or
    // supertypes of range element type
    Type rangeElemType = ((CollectionType) fRangeExp.type()).elemType();

    for (int i = 0; i < fElemVarDecls.size(); i++) {
      VarDecl vd = fElemVarDecls.varDecl(i);
      if (!rangeElemType.isSubtypeOf(vd.type()))
        throw new ExpInvalidException(
            "Type `"
                + vd.type()
                + "' of range variable `"
                + vd.name()
                + "' does not match type `"
                + rangeElemType
                + "' of collection elements.");
    }
  }
Exemple #17
0
  public Expression substitute(String var, Expression replacement) {
    Vector<Expression> new_operands = new Vector<Expression>();
    for (Expression o : operands) {
      new_operands.add(o.substitute(var, replacement));
    }

    return new Application(operator.substitute(var, replacement), new_operands);
  }
 /** INTERNAL Return true if treat was used on this expression */
 public boolean isTreatUsed() {
   if (this.hasDerivedExpressions())
     for (Expression exp : this.derivedExpressions) {
       if (exp.isTreatExpression()) {
         return true;
       }
     }
   return false;
 }
Exemple #19
0
 /*
  * (non-Javadoc)
  *
  * @see jaskell.compiler.JaskellVisitor#visit(jaskell.compiler.core.Alternative)
  */
 public Object visit(Alternative a) {
   Iterator it = a.getChoices();
   while (it.hasNext()) {
     Map.Entry entry = (Map.Entry) it.next();
     Expression body = (Expression) entry.getValue();
     entry.setValue(body.visit(this));
   }
   return a;
 }
Exemple #20
0
  private Expression translate0(RexNode expr) {
    if (expr instanceof RexInputRef) {
      // TODO: multiple inputs, e.g. joins
      final Expression input = getInput(0);
      final int index = ((RexInputRef) expr).getIndex();
      final List<RelDataTypeField> fields = program.getInputRowType().getFieldList();
      final RelDataTypeField field = fields.get(index);
      if (fields.size() == 1) {
        return input;
      } else if (input.getType() == Object[].class) {
        return Expressions.convert_(
            Expressions.arrayIndex(input, Expressions.constant(field.getIndex())),
            Types.box(JavaRules.EnumUtil.javaClass(typeFactory, field.getType())));
      } else {
        return Expressions.field(input, field.getName());
      }
    }
    if (expr instanceof RexLocalRef) {
      return translate(program.getExprList().get(((RexLocalRef) expr).getIndex()));
    }
    if (expr instanceof RexLiteral) {
      return Expressions.constant(
          ((RexLiteral) expr).getValue(), typeFactory.getJavaClass(expr.getType()));
    }
    if (expr instanceof RexCall) {
      final RexCall call = (RexCall) expr;
      final SqlOperator operator = call.getOperator();
      final ExpressionType expressionType = SQL_TO_LINQ_OPERATOR_MAP.get(operator);
      if (expressionType != null) {
        switch (operator.getSyntax()) {
          case Binary:
            return Expressions.makeBinary(
                expressionType, translate(call.getOperands()[0]), translate(call.getOperands()[1]));
          case Postfix:
          case Prefix:
            return Expressions.makeUnary(expressionType, translate(call.getOperands()[0]));
          default:
            throw new RuntimeException("unknown syntax " + operator.getSyntax());
        }
      }

      Method method = SQL_OP_TO_JAVA_METHOD_MAP.get(operator);
      if (method != null) {
        List<Expression> exprs = translateList(Arrays.asList(call.operands));
        return !Modifier.isStatic(method.getModifiers())
            ? Expressions.call(exprs.get(0), method, exprs.subList(1, exprs.size()))
            : Expressions.call(method, exprs);
      }

      switch (expr.getKind()) {
        default:
          throw new RuntimeException("cannot translate expression " + expr);
      }
    }
    throw new RuntimeException("cannot translate expression " + expr);
  }
Exemple #21
0
 /** @see jaskell.compiler.JaskellVisitor#visit(Variable) */
 public Object visit(Variable a) {
   Type ret = null;
   String vname = a.getName();
   Expression def = a.lookup(vname);
   if (def == null) // unknown symbol
   throw new CompilerException("Unknown variable " + vname);
   else ret = (Type) def.visit(this);
   a.setType(ret);
   return ret;
 }
 public City interpret() {
   City resultingCity = new City("Nowhere", 999.9, 999.9);
   for (Expression currentExpression : this.expressions) {
     City currentCity = currentExpression.interpret();
     if (currentCity.getLatitude() < resultingCity.getLatitude()) {
       resultingCity = currentCity;
     }
   }
   return resultingCity;
 }
Exemple #23
0
 protected void assertBooleanQuery() throws ExpInvalidException {
   // queryExp must be a boolean expression
   if (!fQueryExp.type().isBoolean())
     throw new ExpInvalidException(
         "Argument expression of `"
             + name()
             + "' must have boolean type, found `"
             + fQueryExp.type()
             + "'.");
 }
Exemple #24
0
 // Checks if one of the operands is reducible
 public boolean isOperandsReducible() {
   for (Expression o : operands) {
     if (o.reducible()) {
       return true;
     } else if (!IsValue.isValue(o)) {
       return false;
     }
   }
   return false;
 }
  /**
   * Creates an array access with a single index expression.
   *
   * @param array An expression evaluating to an address.
   * @param index The expression with which to index the array.
   */
  public ArrayAccess(Expression array, Expression index) {
    super(2);

    object_print_method = class_print_method;

    children.add(array);
    array.setParent(this);

    children.add(index);
    index.setParent(this);
  }
 public void test() {
   ExpressionBuilder eb = new ExpressionBuilder();
   ReportQuery rq = new ReportQuery(Employee.class, eb);
   rq.addAttribute("firstName");
   rq.addAttribute("lastName");
   Expression exp = eb.getFunction("dbms_random.value");
   exp.setSelectIfOrderedBy(false);
   rq.addOrdering(exp.ascending());
   rq.setSelectionCriteria(eb.anyOf("projects").get("teamLeader").isNull());
   results = (Vector) getSession().executeQuery(rq);
 }
Exemple #27
0
 /*
  * (non-Javadoc)
  *
  * @see jaskell.compiler.JaskellVisitor#visit(jaskell.compiler.core.Application)
  */
 public Object visit(Application a) {
   /* visit function */
   a.setFunction((Expression) a.getFunction().visit(this));
   /* visit all bodies of alternative */
   List it = a.getArgs();
   for (int i = 0; i < it.size(); i++) {
     Expression e = (Expression) it.get(i);
     it.set(i, e.visit(this));
   }
   return a;
 }
Exemple #28
0
  public Expression ownEvaluateExpression(GuidelineInterpreter glManager)
      throws PCA_Session_Exception {

    String operator = getoperatorValue();
    Expression expr;
    Expression first = (Expression) getfirst_argumentValue();
    Expression second = (Expression) getsecond_argumentValue();
    Absolute_Time_Point result = null;

    int timePoint = 0;
    Definite_Time_Point start = null;
    if (first != null) {
      first = first.evaluate_expression(glManager);
      if (first instanceof Set_Expression) {
        start = (Definite_Time_Point) ((Set_Expression) first).getSingleton();
      } else start = (Definite_Time_Point) first;
    } else {
      throw new PCA_Session_Exception("Exception: null first argument in " + this.toString());
    }
    if (second != null) {
      second = second.evaluate_expression(glManager);
    } else {
      throw new PCA_Session_Exception("Exception: null second argument in " + this.toString());
    }
    if ((start == null) || (second == null)) {
      throw new PCA_Session_Exception("Exception: null argument in " + this.toString());
    }

    if (operator == null) {
      throw new PCA_Session_Exception("Exception: null operator in " + this.toString());
    }
    logger.debug(
        "Date_Expression.evaluate_expression: start system value = "
            + start.getsystem_timeValue()
            + " duration = "
            + ((Duration) second).getRoundedDuration(Definite_Time_Point.getSystemTimeUnit()));
    if (operator.equals("+")) {

      timePoint =
          start.getsystem_timeValue()
              + ((Duration) second).getRoundedDuration(Definite_Time_Point.getSystemTimeUnit());
      result = (Definite_Time_Point) glManager.getDBmanager().createInstance("Definite_Time_Point");
      result.setDateValue(timePoint);
      return result;

    } else if (operator.equals("-")) {
      timePoint =
          ((Definite_Time_Point) first).getsystem_timeValue()
              - ((Duration) second).getRoundedDuration(Absolute_Time_Point.getSystemTimeUnit());
      result = (Definite_Time_Point) glManager.getDBmanager().createInstance("Definite_Time_Point");
      result.setDateValue(timePoint);
      return result;
    } else throw new PCA_Session_Exception("Exception: unknown operator in " + this.toString());
  }
 /**
  * INTERNAL: Rebuild myself against the base, with the values of parameters supplied by the
  * context expression. This is used for transforming a standalone expression (e.g. the join
  * criteria of a mapping) into part of some larger expression. You normally would not call this
  * directly, instead calling twist See the comment there for more details"
  */
 public Expression twistedForBaseAndContext(Expression newBase, Expression context) {
   Expression twistedBase = getBaseExpression().twistedForBaseAndContext(newBase, context);
   QueryKeyExpression result = (QueryKeyExpression) twistedBase.get(getName());
   if (shouldUseOuterJoin) {
     result.doUseOuterJoin();
   }
   if (shouldQueryToManyRelationship) {
     result.doQueryToManyRelationship();
   }
   return result;
 }
 public City interpret() {
   //	System.out.println("procesando no oeste");
   City resultingCity = new City("Nowhere", 999.9, 999.9);
   for (Expression currentExpression : expressions) {
     City currentCity = currentExpression.interpret();
     if (currentCity.getLongitude() < resultingCity.getLongitude()) {
       resultingCity = currentCity;
     }
   }
   System.out.println(resultingCity.getName());
   return resultingCity;
 }