Java Code Examples for org.apache.calcite.linq4j.tree.Expressions#new_()

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions#new_() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectiveCallNotNullImplementor.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Expression implement(RexToLixTranslator translator,
    RexCall call, List<Expression> translatedOperands) {
  translatedOperands =
      EnumUtils.fromInternal(method.getParameterTypes(), translatedOperands);
  translatedOperands =
      EnumUtils.convertAssignableTypes(method.getParameterTypes(), translatedOperands);
  final Expression callExpr;
  if ((method.getModifiers() & Modifier.STATIC) != 0) {
    callExpr = Expressions.call(method, translatedOperands);
  } else {
    // The UDF class must have a public zero-args constructor.
    // Assume that the validator checked already.
    final Expression target =
        Expressions.new_(method.getDeclaringClass());
    callExpr = Expressions.call(target, method, translatedOperands);
  }
  if (!containsCheckedException(method)) {
    return callExpr;
  }
  return translator.handleMethodCheckedExceptions(callExpr);
}
 
Example 2
Source File: RelDataTypeHolder.java    From marble with Apache License 2.0 5 votes vote down vote up
public static  Expression generateExpression(RelDataType relDataType) {
  SqlTypeName sqlTypeName = relDataType.getSqlTypeName();
  RelDataType componentType = relDataType.getComponentType();
  if (componentType == null) {
    return Expressions.new_(RelDataTypeHolder.class,
        new ConstantExpression(SqlTypeName.class, sqlTypeName));
  } else {
    Expression componentTypeExpr = generateExpression(componentType);
    return Expressions.new_(RelDataTypeHolder.class,
        new ConstantExpression(SqlTypeName.class, sqlTypeName),
        componentTypeExpr);
  }
}
 
Example 3
Source File: RelDataTypeHolder.java    From marble with Apache License 2.0 5 votes vote down vote up
public static Expression generateExpressionWithConstantValue(RelDataType relDataType,
    Expression valueExpression) {
  return Expressions.new_(RelDataTypeHolder.class,
      new ConstantExpression(SqlTypeName.class,
          relDataType.getSqlTypeName()),
      new ConstantExpression(boolean.class, true),
      valueExpression);
}
 
Example 4
Source File: HiveUDAFImplementor.java    From marble with Apache License 2.0 5 votes vote down vote up
@Override public void implementNotNullReset(AggContext info,
    AggResetContext context) {

  Expression acc0 = context.accumulator().get(0);
  Expression participatorExpr = Expressions.new_(HiveUDAFParticipator.class);
  Expression assignExpr = Expressions.assign(acc0, participatorExpr);
  context.currentBlock().add(Expressions.statement(assignExpr));

}
 
Example 5
Source File: HiveUDFImplementor.java    From marble with Apache License 2.0 5 votes vote down vote up
private MemberDeclaration generateUdfInstanceDeclaration(String opName,
    SqlSyntax syntax, String fieldName) {
  try {
    if (opName.equals("NOT RLIKE")) {
      //we use a RexImpTable.NotImplementor to wrapper a HiveUDFImplementor ,
      // so `NOT RLIKE` and `RLIKE` would be treated as same here
      opName = "RLIKE";
    }
    if (opName.equals("NOT REGEXP")) {
      opName = "REGEXP";
    }
    Class hiveUDFClazz = HiveSqlOperatorTable.instance()
        .getHiveUDFClass(opName, syntax);
    Expression newUdfExpr;
    if (GenericUDF.class.isAssignableFrom(hiveUDFClazz)) {
      newUdfExpr = Expressions.new_(hiveUDFClazz.getConstructor());
    } else if (UDF.class.isAssignableFrom(hiveUDFClazz)) {
      newUdfExpr = Expressions.new_(GENERIC_UDF_BRIDGE_CONSTRUCTOR
          , new ConstantExpression(String.class, opName)
          , new ConstantExpression(boolean.class, false)
          , new ConstantExpression(String.class, hiveUDFClazz.getName()));
    } else {
      throw new IllegalArgumentException("unknown hive udf class for opName="
          + opName
          + ",and syntax="
          + syntax);
    }
    MemberDeclaration udfMemberDeclaration = Expressions.fieldDecl(
        Modifier.PUBLIC,
        Expressions.parameter(GenericUDF.class, fieldName),
        newUdfExpr);
    return udfMemberDeclaration;
  } catch (NoSuchMethodException e) {
    throw new RuntimeException("fail to new instance for op name " + opName, e);
  }
}
 
Example 6
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testClassDecl() {
  final NewExpression newExpression =
      Expressions.new_(
          Object.class,
          ImmutableList.of(),
          Arrays.asList(
              Expressions.fieldDecl(
                  Modifier.PUBLIC | Modifier.FINAL,
                  Expressions.parameter(String.class, "foo"),
                  Expressions.constant("bar")),
              new ClassDeclaration(
                  Modifier.PUBLIC | Modifier.STATIC,
                  "MyClass",
                  null,
                  ImmutableList.of(),
                  Arrays.asList(
                      new FieldDeclaration(
                          0,
                          Expressions.parameter(int.class, "x"),
                          Expressions.constant(0)))),
              Expressions.fieldDecl(
                  0,
                  Expressions.parameter(int.class, "i"))));
  assertEquals(
      "new Object(){\n"
          + "  public final String foo = \"bar\";\n"
          + "  public static class MyClass {\n"
          + "    int x = 0;\n"
          + "  }\n"
          + "  int i;\n"
          + "}",
      Expressions.toString(newExpression));
  newExpression.accept(new Shuttle());
}
 
Example 7
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Handle checked Exceptions declared in Method. In such case,
 * method call should be wrapped in a try...catch block.
 * "
 *      final Type method_call;
 *      try {
 *        method_call = callExpr
 *      } catch (Exception e) {
 *        throw new RuntimeException(e);
 *      }
 * "
 */
Expression handleMethodCheckedExceptions(Expression callExpr) {
  // Try statement
  ParameterExpression methodCall = Expressions.parameter(
      callExpr.getType(), list.newName("method_call"));
  list.add(Expressions.declare(Modifier.FINAL, methodCall, null));
  Statement st = Expressions.statement(Expressions.assign(methodCall, callExpr));
  // Catch Block, wrap checked exception in unchecked exception
  ParameterExpression e = Expressions.parameter(0, Exception.class, "e");
  Expression uncheckedException = Expressions.new_(RuntimeException.class, e);
  CatchBlock cb = Expressions.catch_(e, Expressions.throw_(uncheckedException));
  list.add(Expressions.tryCatch(st, cb));
  return methodCall;
}
 
Example 8
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override Expression implementSafe(RexToLixTranslator translator,
    RexCall call, List<Expression> argValueList) {
  List<Expression> argValueList0 =
      EnumUtils.fromInternal(method.getParameterTypes(), argValueList);
  if ((method.getModifiers() & Modifier.STATIC) != 0) {
    return Expressions.call(method, argValueList0);
  } else {
    // The UDF class must have a public zero-args constructor.
    // Assume that the validator checked already.
    final Expression target = Expressions.new_(method.getDeclaringClass());
    return Expressions.call(target, method, argValueList0);
  }
}
 
Example 9
Source File: PhysTypeImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Expression generateComparator(RelCollation collation) {
  // int c;
  // c = Utilities.compare(v0, v1);
  // if (c != 0) return c; // or -c if descending
  // ...
  // return 0;
  BlockBuilder body = new BlockBuilder();
  final Type javaRowClass = Primitive.box(this.javaRowClass);
  final ParameterExpression parameterV0 =
      Expressions.parameter(javaRowClass, "v0");
  final ParameterExpression parameterV1 =
      Expressions.parameter(javaRowClass, "v1");
  final ParameterExpression parameterC =
      Expressions.parameter(int.class, "c");
  final int mod =
      collation.getFieldCollations().size() == 1 ? Modifier.FINAL : 0;
  body.add(Expressions.declare(mod, parameterC, null));
  for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
    final int index = fieldCollation.getFieldIndex();
    final RelDataType fieldType = rowType.getFieldList().get(index).getType();
    final Expression fieldComparator = generateCollatorExpression(fieldType.getCollation());
    Expression arg0 = fieldReference(parameterV0, index);
    Expression arg1 = fieldReference(parameterV1, index);
    switch (Primitive.flavor(fieldClass(index))) {
    case OBJECT:
      arg0 = EnumUtils.convert(arg0, Comparable.class);
      arg1 = EnumUtils.convert(arg1, Comparable.class);
    }
    final boolean nullsFirst =
        fieldCollation.nullDirection
            == RelFieldCollation.NullDirection.FIRST;
    final boolean descending =
        fieldCollation.getDirection()
            == RelFieldCollation.Direction.DESCENDING;
    body.add(
        Expressions.statement(
            Expressions.assign(
                parameterC,
                Expressions.call(
                    Utilities.class,
                    fieldNullable(index)
                        ? (nullsFirst != descending
                        ? "compareNullsFirst"
                        : "compareNullsLast")
                        : "compare",
                    Expressions.list(
                        arg0,
                        arg1)
                        .appendIfNotNull(fieldComparator)))));
    body.add(
        Expressions.ifThen(
            Expressions.notEqual(
                parameterC, Expressions.constant(0)),
            Expressions.return_(
                null,
                descending
                    ? Expressions.negate(parameterC)
                    : parameterC)));
  }
  body.add(
      Expressions.return_(null, Expressions.constant(0)));

  final List<MemberDeclaration> memberDeclarations =
      Expressions.list(
          Expressions.methodDecl(
              Modifier.PUBLIC,
              int.class,
              "compare",
              ImmutableList.of(parameterV0, parameterV1),
              body.toBlock()));

  if (EnumerableRules.BRIDGE_METHODS) {
    final ParameterExpression parameterO0 =
        Expressions.parameter(Object.class, "o0");
    final ParameterExpression parameterO1 =
        Expressions.parameter(Object.class, "o1");
    BlockBuilder bridgeBody = new BlockBuilder();
    bridgeBody.add(
        Expressions.return_(
            null,
            Expressions.call(
                Expressions.parameter(
                    Comparable.class, "this"),
                BuiltInMethod.COMPARATOR_COMPARE.method,
                Expressions.convert_(
                    parameterO0,
                    javaRowClass),
                Expressions.convert_(
                    parameterO1,
                    javaRowClass))));
    memberDeclarations.add(
        overridingMethodDecl(
            BuiltInMethod.COMPARATOR_COMPARE.method,
            ImmutableList.of(parameterO0, parameterO1),
            bridgeBody.toBlock()));
  }
  return Expressions.new_(
      Comparator.class,
      ImmutableList.of(),
      memberDeclarations);
}
 
Example 10
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 4 votes vote down vote up
private Expression implementEmitter(EnumerableRelImplementor implementor,
    PhysType physType, PhysType inputPhysType) {
  final ParameterExpression rows_ =
      Expressions.parameter(Types.of(List.class, inputPhysType.getJavaRowType()), "rows");
  final ParameterExpression rowStates_ =
      Expressions.parameter(List.class, "rowStates");
  final ParameterExpression symbols_ =
      Expressions.parameter(List.class, "symbols");
  final ParameterExpression match_ =
      Expressions.parameter(int.class, "match");
  final ParameterExpression consumer_ =
      Expressions.parameter(Consumer.class, "consumer");
  final ParameterExpression i_ = Expressions.parameter(int.class, "i");

  final ParameterExpression row_ =
      Expressions.parameter(inputPhysType.getJavaRowType(), "row");

  final BlockBuilder builder2 = new BlockBuilder();

  // Add loop variable initialization
  builder2.add(
      Expressions.declare(0, row_,
          EnumUtils.convert(
              Expressions.call(rows_, BuiltInMethod.LIST_GET.method, i_),
              inputPhysType.getJavaRowType())));

  RexBuilder rexBuilder = new RexBuilder(implementor.getTypeFactory());
  RexProgramBuilder rexProgramBuilder =
      new RexProgramBuilder(inputPhysType.getRowType(), rexBuilder);
  for (Map.Entry<String, RexNode> entry : measures.entrySet()) {
    rexProgramBuilder.addProject(entry.getValue(), entry.getKey());
  }

  final RexToLixTranslator translator = RexToLixTranslator.forAggregation(
      (JavaTypeFactory) getCluster().getTypeFactory(),
      builder2,
      new PassedRowsInputGetter(row_, rows_, inputPhysType),
      implementor.getConformance());

  final ParameterExpression result_ =
      Expressions.parameter(physType.getJavaRowType());

  builder2.add(
      Expressions.declare(Modifier.FINAL, result_,
          Expressions.new_(physType.getJavaRowType())));
  Ord.forEach(measures.values(), (measure, i) ->
      builder2.add(
          Expressions.statement(
              Expressions.assign(physType.fieldReference(result_, i),
                  implementMeasure(translator, rows_, symbols_, i_, row_,
                      measure)))));
  builder2.add(
      Expressions.statement(
          Expressions.call(consumer_, BuiltInMethod.CONSUMER_ACCEPT.method,
              result_)));

  final BlockBuilder builder = new BlockBuilder();

  // Loop Length

  // we have to use an explicit for (int i = ...) loop, as we need to know later
  // which of the matched rows are already passed (in MatchUtils), so foreach cannot be used
  builder.add(
      Expressions.for_(
          Expressions.declare(0, i_, Expressions.constant(0)),
          Expressions.lessThan(i_,
              Expressions.call(rows_, BuiltInMethod.COLLECTION_SIZE.method)),
          Expressions.preIncrementAssign(i_),
          builder2.toBlock()));

  return Expressions.new_(
      Types.of(Enumerables.Emitter.class), NO_EXPRS,
      Expressions.list(
          EnumUtils.overridingMethodDecl(
              BuiltInMethod.EMITTER_EMIT.method,
              ImmutableList.of(rows_, rowStates_, symbols_, match_,
                  consumer_),
              builder.toBlock())));
}
 
Example 11
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Generates code for a predicate. */
private Expression implementPredicate(PhysType physType,
    ParameterExpression rows_, BlockStatement body) {
  final List<MemberDeclaration> memberDeclarations = new ArrayList<>();
  ParameterExpression row_ = Expressions.parameter(
      Types.of(MemoryFactory.Memory.class,
          physType.getJavaRowType()), "row_");
  Expressions.assign(row_,
      Expressions.call(rows_, BuiltInMethod.MEMORY_GET0.method));

  // Implement the Predicate here based on the pattern definition

  // Add a predicate method:
  //
  //   public boolean test(E row, List<E> rows) {
  //     return ...;
  //   }
  memberDeclarations.add(
      EnumUtils.overridingMethodDecl(
          BuiltInMethod.PREDICATE_TEST.method,
          ImmutableList.of(row_), body));
  if (EnumerableRules.BRIDGE_METHODS) {
    // Add a bridge method:
    //
    //   public boolean test(Object row, Object rows) {
    //     return this.test(row, (List) rows);
    //   }
    final ParameterExpression row0_ =
        Expressions.parameter(Object.class, "row");
    final ParameterExpression rowsO_ =
        Expressions.parameter(Object.class, "rows");
    BlockBuilder bridgeBody = new BlockBuilder();
    bridgeBody.add(
        Expressions.return_(null,
            Expressions.call(
                Expressions.parameter(Comparable.class, "this"),
                BuiltInMethod.PREDICATE_TEST.method,
                Expressions.convert_(row0_,
                    Types.of(MemoryFactory.Memory.class,
                        physType.getJavaRowType())))));
    memberDeclarations.add(
        EnumUtils.overridingMethodDecl(
            BuiltInMethod.PREDICATE_TEST.method,
            ImmutableList.of(row0_), bridgeBody.toBlock()));
  }
  return Expressions.new_(Types.of(Predicate.class), NO_EXPRS,
      memberDeclarations);
}