Skip to content

Commit

Permalink
[DROOLS-6908] Arithmetic operation with String coercion in constraint…
Browse files Browse the repository at this point in the history
… fails in executable-model (#4317) (#4554)
  • Loading branch information
tkobayas authored Jul 21, 2022
1 parent c58d5ee commit 36c99a1
Show file tree
Hide file tree
Showing 10 changed files with 449 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import static java.lang.System.arraycopy;
import static java.lang.reflect.Modifier.PUBLIC;
import static java.lang.reflect.Modifier.STATIC;
import static java.util.Arrays.asList;
import static org.drools.core.util.MethodUtils.getMethod;
import static org.drools.core.util.StringUtils.ucFirst;

Expand All @@ -74,6 +75,10 @@ public final class ClassUtils {

private static final Map<String, Class<?>> primitiveNameToType;

private static final Set<Class<?>> numericClasses = new HashSet<Class<?>>(asList(int.class, long.class, double.class, float.class, short.class, char.class, byte.class,
Integer.class, Long.class, Double.class, Float.class, Short.class, Character.class, Byte.class,
BigInteger.class, BigDecimal.class));

static {
final Map<String, String> m = new HashMap<>();
m.put("int", "I");
Expand Down Expand Up @@ -1003,4 +1008,8 @@ public static String getCanonicalSimpleName(Class<?> c, char separator) {
getCanonicalSimpleName(enclosingClass) + separator + c.getSimpleName() :
c.getSimpleName();
}

public static boolean isNumericClass(Class<?> clazz) {
return numericClasses.contains(clazz);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public boolean containThis() {
@Override
public String toString() {
return "TypedExpression{" +
"expression=" + expression +
"expression=" + PrintUtil.printNode(expression) +
", jpType=" + (expression == null ? "" : expression.getClass().getSimpleName()) +
", type=" + type +
", fieldName='" + fieldName + '\'' +
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2022 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.drools.modelcompiler.builder.generator.drlxparse;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

import com.github.javaparser.ast.expr.BinaryExpr.Operator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult;
import org.drools.modelcompiler.builder.generator.TypedExpression;

import static com.github.javaparser.ast.NodeList.nodeList;
import static com.github.javaparser.ast.expr.BinaryExpr.Operator.DIVIDE;
import static com.github.javaparser.ast.expr.BinaryExpr.Operator.MINUS;
import static com.github.javaparser.ast.expr.BinaryExpr.Operator.MULTIPLY;
import static com.github.javaparser.ast.expr.BinaryExpr.Operator.PLUS;
import static com.github.javaparser.ast.expr.BinaryExpr.Operator.REMAINDER;
import static java.util.Arrays.asList;
import static org.drools.core.util.ClassUtils.isNumericClass;

public class ArithmeticCoercedExpression {

private final TypedExpression left;
private final TypedExpression right;
private final Operator operator;

private final static Set<Operator> arithmeticOperators = new HashSet<Operator>(asList(PLUS, MINUS, MULTIPLY, DIVIDE, REMAINDER));

public ArithmeticCoercedExpression(TypedExpression left, TypedExpression right, Operator operator) {
this.left = left;
this.right = right;
this.operator = operator;
}

public ArithmeticCoercedExpressionResult coerce() {

if (!requiresCoercion()) {
return new ArithmeticCoercedExpressionResult(left, right); // do not coerce
}

final Class<?> leftClass = left.getRawClass();
final Class<?> rightClass = right.getRawClass();

if (!canCoerce(leftClass, rightClass)) {
throw new ArithmeticCoercedExpressionException(new InvalidExpressionErrorResult("Arithmetic operation requires compatible types. Found " + leftClass + " and " + rightClass));
}

TypedExpression coercedLeft = left;
TypedExpression coercedRight = right;
if (leftClass == String.class) {
if (operator == Operator.PLUS) {
// String concatenation : Compatibility with mvel
coercedRight = coerceToString(right);
} else {
// We may coerce to BigDecimal but Mvel MathProcessor uses double so followed the same.
coercedLeft = coerceToDouble(left);
}
}
if (rightClass == String.class) {
if (operator == Operator.PLUS) {
// String concatenation : Compatibility with mvel
coercedLeft = coerceToString(left);
} else {
// We may coerce to BigDecimal but Mvel MathProcessor uses double so followed the same.
coercedRight = coerceToDouble(right);
}
}

return new ArithmeticCoercedExpressionResult(coercedLeft, coercedRight);
}

private boolean requiresCoercion() {
if (!arithmeticOperators.contains(operator)) {
return false;
}
final Class<?> leftClass = left.getRawClass();
final Class<?> rightClass = right.getRawClass();
if (leftClass == rightClass) {
return false;
}
if (isNumericClass(leftClass) && isNumericClass(rightClass)) {
return false;
}
return true;
}

private boolean canCoerce(Class<?> leftClass, Class<?> rightClass) {
return leftClass == String.class && isNumericClass(rightClass) ||
rightClass == String.class && isNumericClass(leftClass);
}

private TypedExpression coerceToDouble(TypedExpression typedExpression) {
final Expression expression = typedExpression.getExpression();
TypedExpression coercedExpression = typedExpression.cloneWithNewExpression(new MethodCallExpr(new NameExpr("Double"), "valueOf", nodeList(expression)));
return coercedExpression.setType(BigDecimal.class);
}

private TypedExpression coerceToString(TypedExpression typedExpression) {
final Expression expression = typedExpression.getExpression();
TypedExpression coercedExpression = typedExpression.cloneWithNewExpression(new MethodCallExpr(new NameExpr("String"), "valueOf", nodeList(expression)));
return coercedExpression.setType(String.class);
}

public static class ArithmeticCoercedExpressionResult {

private final TypedExpression coercedLeft;
private final TypedExpression coercedRight;

public ArithmeticCoercedExpressionResult(TypedExpression left, TypedExpression coercedRight) {
this.coercedLeft = left;
this.coercedRight = coercedRight;
}

public TypedExpression getCoercedLeft() {
return coercedLeft;
}

public TypedExpression getCoercedRight() {
return coercedRight;
}
}

public static class ArithmeticCoercedExpressionException extends RuntimeException {

private final transient InvalidExpressionErrorResult invalidExpressionErrorResult;

ArithmeticCoercedExpressionException(InvalidExpressionErrorResult invalidExpressionErrorResult) {
this.invalidExpressionErrorResult = invalidExpressionErrorResult;
}

public InvalidExpressionErrorResult getInvalidExpressionErrorResult() {
return invalidExpressionErrorResult;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
import org.drools.modelcompiler.builder.generator.RuleContext;
import org.drools.modelcompiler.builder.generator.TypedExpression;
import org.drools.modelcompiler.builder.generator.UnificationTypedExpression;
import org.drools.modelcompiler.builder.generator.drlxparse.ArithmeticCoercedExpression;
import org.drools.modelcompiler.builder.generator.operatorspec.CustomOperatorSpec;
import org.drools.modelcompiler.builder.generator.operatorspec.NativeOperatorSpec;
import org.drools.modelcompiler.builder.generator.operatorspec.OperatorSpec;
Expand Down Expand Up @@ -212,10 +213,26 @@ private Optional<TypedExpression> toTypedExpressionRec(Expression drlxExpr) {
Optional<TypedExpression> optLeft = toTypedExpressionRec(binaryExpr.getLeft());
Optional<TypedExpression> optRight = toTypedExpressionRec(binaryExpr.getRight());

return optLeft.flatMap(left -> optRight.flatMap(right -> {
final BinaryExpr combo = new BinaryExpr(left.getExpression(), right.getExpression(), operator);
return of(new TypedExpression(combo, left.getType()));
}));
if (!optLeft.isPresent() || !optRight.isPresent()) {
return empty();
}

TypedExpression left = optLeft.get();
TypedExpression right = optRight.get();

ArithmeticCoercedExpression.ArithmeticCoercedExpressionResult coerced;
try {
coerced = new ArithmeticCoercedExpression(left, right, operator).coerce();
} catch (ArithmeticCoercedExpression.ArithmeticCoercedExpressionException e) {
logger.error("Failed to coerce : " + e.getInvalidExpressionErrorResult());
return empty();
}

left = coerced.getCoercedLeft();
right = coerced.getCoercedRight();

final BinaryExpr combo = new BinaryExpr(left.getExpression(), right.getExpression(), operator);
return of(new TypedExpression(combo, left.getType()));
}

if (drlxExpr instanceof HalfBinaryExpr) {
Expand Down
Loading

0 comments on commit 36c99a1

Please sign in to comment.