Search in sources :

Example 1 with ConstraintCompiler

use of org.drools.mvelcompiler.ConstraintCompiler in project drools by kiegroup.

the class ConstraintParser method toBigDecimalExpression.

// TODO luca this logic should be moved in Constraint compiler?
private Expression toBigDecimalExpression(TypedExpression typedExpression) {
    MethodCallExpr toBigDecimalMethod = new MethodCallExpr(null, "org.drools.modelcompiler.util.EvaluationUtil.toBigDecimal");
    Expression arg = typedExpression.getExpression();
    Optional<Class<?>> originalPatternType = typedExpression.getOriginalPatternType();
    ConstraintCompiler constraintCompiler = createConstraintCompiler(context, originalPatternType);
    CompiledExpressionResult compiledBlockResult = constraintCompiler.compileExpression(PrintUtil.printNode(arg));
    arg = compiledBlockResult.getExpression();
    if (arg.isEnclosedExpr()) {
        arg = arg.asEnclosedExpr().getInner();
    }
    if (arg instanceof BigIntegerLiteralExpr) {
        arg = new ObjectCreationExpr(null, toClassOrInterfaceType(BigInteger.class), NodeList.nodeList(new StringLiteralExpr(((BigIntegerLiteralExpr) arg).asBigInteger().toString())));
    } else if (arg instanceof BigDecimalLiteralExpr) {
        arg = new ObjectCreationExpr(null, toClassOrInterfaceType(BigDecimal.class), NodeList.nodeList(new StringLiteralExpr(((BigDecimalLiteralExpr) arg).asBigDecimal().toString())));
    }
    toBigDecimalMethod.addArgument(arg);
    return toBigDecimalMethod;
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) BigIntegerLiteralExpr(org.drools.mvel.parser.ast.expr.BigIntegerLiteralExpr) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) DrlxExpression(org.drools.mvel.parser.ast.expr.DrlxExpression) CompiledExpressionResult(org.drools.mvelcompiler.CompiledExpressionResult) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) ConstraintCompiler(org.drools.mvelcompiler.ConstraintCompiler) DrlxParseUtil.createConstraintCompiler(org.drools.modelcompiler.builder.generator.DrlxParseUtil.createConstraintCompiler) BigDecimal(java.math.BigDecimal) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) BigDecimalLiteralExpr(org.drools.mvel.parser.ast.expr.BigDecimalLiteralExpr)

Example 2 with ConstraintCompiler

use of org.drools.mvelcompiler.ConstraintCompiler in project drools by kiegroup.

the class ConstraintParser method parseBinaryExpr.

private DrlxParseResult parseBinaryExpr(BinaryExpr binaryExpr, Class<?> patternType, String bindingId, ConstraintExpression constraint, Expression drlxExpr, boolean hasBind, boolean isPositional, boolean isEnclosed) {
    BinaryExpr.Operator operator = binaryExpr.getOperator();
    boolean isOrBinary = operator == BinaryExpr.Operator.OR;
    if (isLogicalOperator(operator) && isCombinable(binaryExpr)) {
        DrlxParseResult leftResult = compileToJavaRecursive(patternType, bindingId, constraint, binaryExpr.getLeft(), hasBind, isPositional);
        Expression rightExpr = binaryExpr.getRight() instanceof HalfPointFreeExpr ? completeHalfExpr(((PointFreeExpr) binaryExpr.getLeft()).getLeft(), (HalfPointFreeExpr) binaryExpr.getRight()) : binaryExpr.getRight();
        DrlxParseResult rightResult = compileToJavaRecursive(patternType, bindingId, constraint, rightExpr, hasBind, isPositional);
        return isMultipleResult(leftResult, operator, rightResult) ? createMultipleDrlxParseSuccess(operator, (DrlxParseSuccess) leftResult, (DrlxParseSuccess) rightResult) : leftResult.combineWith(rightResult, operator);
    }
    final ExpressionTyperContext expressionTyperContext = new ExpressionTyperContext();
    final ExpressionTyper expressionTyper = new ExpressionTyper(context, patternType, bindingId, isPositional, expressionTyperContext);
    TypedExpressionResult leftTypedExpressionResult = expressionTyper.toTypedExpression(binaryExpr.getLeft());
    Optional<TypedExpression> optLeft = leftTypedExpressionResult.getTypedExpression();
    if (!optLeft.isPresent()) {
        return new DrlxParseFail();
    }
    TypedExpression left = optLeft.get();
    List<String> usedDeclarationsOnLeft = hasBind ? new ArrayList<>(expressionTyperContext.getUsedDeclarations()) : null;
    List<Expression> leftPrefixExpressions = new ArrayList<>();
    if (isOrBinary) {
        leftPrefixExpressions.addAll(expressionTyperContext.getNullSafeExpressions());
        expressionTyperContext.getNullSafeExpressions().clear();
        leftPrefixExpressions.addAll(expressionTyperContext.getPrefixExpresssions());
        expressionTyperContext.getPrefixExpresssions().clear();
    }
    List<Expression> rightPrefixExpresssions = new ArrayList<>();
    TypedExpression right;
    if (constraint.isNameClashingUnification()) {
        String name = constraint.getUnificationField();
        right = new TypedExpression(new NameExpr(name), left.getType());
        expressionTyperContext.addUsedDeclarations(name);
    } else {
        TypedExpressionResult rightExpressionResult = expressionTyper.toTypedExpression(binaryExpr.getRight());
        Optional<TypedExpression> optRight = rightExpressionResult.getTypedExpression();
        if (!optRight.isPresent()) {
            return new DrlxParseFail(new ParseExpressionErrorResult(drlxExpr));
        }
        right = optRight.get();
        if (isOrBinary) {
            rightPrefixExpresssions.addAll(expressionTyperContext.getNullSafeExpressions());
            expressionTyperContext.getNullSafeExpressions().clear();
            rightPrefixExpresssions.addAll(expressionTyperContext.getPrefixExpresssions());
            expressionTyperContext.getPrefixExpresssions().clear();
        }
    }
    boolean equalityExpr = operator == EQUALS || operator == NOT_EQUALS;
    CoercedExpression.CoercedExpressionResult coerced;
    try {
        coerced = new CoercedExpression(left, right, equalityExpr).coerce();
    } catch (CoercedExpression.CoercedExpressionException e) {
        return new DrlxParseFail(e.getInvalidExpressionErrorResult());
    }
    left = coerced.getCoercedLeft();
    right = getCoercedRightExpression(packageModel, coerced);
    Expression combo;
    boolean arithmeticExpr = asList(PLUS, MINUS, MULTIPLY, DIVIDE, REMAINDER).contains(operator);
    boolean isBetaConstraint = right.getExpression() != null && hasNonGlobalDeclaration(expressionTyperContext);
    boolean requiresSplit = operator == BinaryExpr.Operator.AND && binaryExpr.getRight() instanceof HalfBinaryExpr && !isBetaConstraint;
    if (equalityExpr) {
        combo = getEqualityExpression(left, right, operator).expression;
    } else if (arithmeticExpr && (left.isBigDecimal())) {
        ConstraintCompiler constraintCompiler = createConstraintCompiler(this.context, of(patternType));
        CompiledExpressionResult compiledExpressionResult = constraintCompiler.compileExpression(binaryExpr);
        combo = compiledExpressionResult.getExpression();
    } else {
        if (left.getExpression() == null || right.getExpression() == null) {
            return new DrlxParseFail(new ParseExpressionErrorResult(drlxExpr));
        }
        // This special comparisons
        SpecialComparisonResult specialComparisonResult = handleSpecialComparisonCases(expressionTyper, operator, left, right);
        combo = specialComparisonResult.expression;
        left = requiresSplit ? left : specialComparisonResult.coercedLeft;
        right = requiresSplit ? right : specialComparisonResult.coercedRight;
    }
    if (isOrBinary) {
        // NullSafeExpressions are combined here because the order is complex
        combo = combineExpressions(leftPrefixExpressions, rightPrefixExpresssions, combo);
    } else {
        // NullSafeExpressions will be added later by PatternDSL.addNullSafeExpr() which will be separated AlphaNodes
        combo = combineExpressions(leftTypedExpressionResult, combo);
    }
    boolean isPredicate = isPredicateBooleanExpression(binaryExpr);
    if (isEnclosed && !isPredicate) {
        combo = new EnclosedExpr(combo);
    }
    Index.ConstraintType constraintType = DrlxParseUtil.toConstraintType(operator);
    if (isForallSelfJoinConstraint(left, right, constraintType)) {
        constraintType = Index.ConstraintType.FORALL_SELF_JOIN;
    }
    return new SingleDrlxParseSuccess(patternType, bindingId, combo, isBooleanOperator(operator) ? boolean.class : left.getType()).setDecodeConstraintType(constraintType).setUsedDeclarations(expressionTyperContext.getUsedDeclarations()).setUsedDeclarationsOnLeft(usedDeclarationsOnLeft).setUnification(constraint.isUnification()).setReactOnProperties(expressionTyperContext.getReactOnProperties()).setLeft(left).setRight(right).setBetaConstraint(isBetaConstraint).setRequiresSplit(requiresSplit).setIsPredicate(isPredicate).setImplicitCastExpression(leftTypedExpressionResult.getInlineCastExpression()).setNullSafeExpressions(// This would be empty if NullSafeExpressions were combined earlier
    leftTypedExpressionResult.getNullSafeExpressions());
}
Also used : CompiledExpressionResult(org.drools.mvelcompiler.CompiledExpressionResult) ArrayList(java.util.ArrayList) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) Index(org.drools.model.Index) ParseExpressionErrorResult(org.drools.modelcompiler.builder.errors.ParseExpressionErrorResult) ConstraintCompiler(org.drools.mvelcompiler.ConstraintCompiler) DrlxParseUtil.createConstraintCompiler(org.drools.modelcompiler.builder.generator.DrlxParseUtil.createConstraintCompiler) ExpressionTyperContext(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyperContext) ExpressionTyper(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyper) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) HalfBinaryExpr(org.drools.mvel.parser.ast.expr.HalfBinaryExpr) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) HalfBinaryExpr(org.drools.mvel.parser.ast.expr.HalfBinaryExpr) HalfPointFreeExpr(org.drools.mvel.parser.ast.expr.HalfPointFreeExpr) PointFreeExpr(org.drools.mvel.parser.ast.expr.PointFreeExpr) HalfPointFreeExpr(org.drools.mvel.parser.ast.expr.HalfPointFreeExpr) TypedExpressionResult(org.drools.modelcompiler.builder.generator.expressiontyper.TypedExpressionResult) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) DrlxExpression(org.drools.mvel.parser.ast.expr.DrlxExpression) MultipleDrlxParseSuccess.createMultipleDrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.MultipleDrlxParseSuccess.createMultipleDrlxParseSuccess) DrlxParseUtil.stripEnclosedExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.stripEnclosedExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr)

Example 3 with ConstraintCompiler

use of org.drools.mvelcompiler.ConstraintCompiler in project drools by kiegroup.

the class Evaluator method compileWithMvelCompiler.

private static CompiledResult compileWithMvelCompiler(Object compiledExpression, Map<String, Object> vars, ClassLoader classLoader) {
    String expressionString = compiledExpression.toString();
    Set<String> imports = new HashSet<>();
    imports.add("java.util.List");
    imports.add("java.util.ArrayList");
    imports.add("java.util.HashMap");
    imports.add("java.util.Map");
    imports.add("java.math.BigDecimal");
    imports.add("org.drools.Address");
    TypeResolver classTypeResolver = new ClassTypeResolver(imports, classLoader);
    MvelCompilerContext context = new MvelCompilerContext(classTypeResolver);
    for (Map.Entry<String, Object> o : vars.entrySet()) {
        Object value1 = o.getValue();
        if (value1 != null) {
            context.addDeclaration(o.getKey(), value1.getClass());
        }
    }
    MvelCompiler mvelCompiler = new MvelCompiler(context);
    ConstraintCompiler constraintCompiler = new ConstraintCompiler(context);
    if (isAStatement(expressionString)) {
        String expressionStringWithBraces = String.format("{%s}", expressionString);
        return mvelCompiler.compileStatement(expressionStringWithBraces);
    } else {
        return constraintCompiler.compileExpression(expressionString);
    }
}
Also used : MvelCompiler(org.drools.mvelcompiler.MvelCompiler) MvelCompilerContext(org.drools.mvelcompiler.context.MvelCompilerContext) TypeResolver(org.drools.core.addon.TypeResolver) ClassTypeResolver(org.drools.core.addon.ClassTypeResolver) ConstraintCompiler(org.drools.mvelcompiler.ConstraintCompiler) ClassTypeResolver(org.drools.core.addon.ClassTypeResolver) Map(java.util.Map) HashSet(java.util.HashSet)

Example 4 with ConstraintCompiler

use of org.drools.mvelcompiler.ConstraintCompiler in project drools by kiegroup.

the class DrlxParseUtil method createConstraintCompiler.

public static ConstraintCompiler createConstraintCompiler(RuleContext context, Optional<Class<?>> originalPatternType) {
    MvelCompilerContext mvelCompilerContext = new MvelCompilerContext(context.getTypeResolver(), context.getCurrentScopeSuffix());
    List<DeclarationSpec> allDeclarations = new ArrayList<>(context.getAllDeclarations());
    originalPatternType.ifPresent(pt -> {
        allDeclarations.add(new DeclarationSpec(THIS_PLACEHOLDER, pt));
        mvelCompilerContext.setRootPatternPrefix(pt, THIS_PLACEHOLDER);
    });
    for (Map.Entry<String, Method> m : context.getPackageModel().getStaticMethods().entrySet()) {
        mvelCompilerContext.addStaticMethod(m.getKey(), m.getValue());
    }
    for (DeclarationSpec ds : allDeclarations) {
        mvelCompilerContext.addDeclaration(ds.getBindingId(), ds.getDeclarationClass());
    }
    return new ConstraintCompiler(mvelCompilerContext);
}
Also used : MvelCompilerContext(org.drools.mvelcompiler.context.MvelCompilerContext) ArrayList(java.util.ArrayList) MethodUtils.findMethod(org.drools.core.util.MethodUtils.findMethod) Method(java.lang.reflect.Method) ConstraintCompiler(org.drools.mvelcompiler.ConstraintCompiler) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Aggregations

ConstraintCompiler (org.drools.mvelcompiler.ConstraintCompiler)4 Expression (com.github.javaparser.ast.expr.Expression)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 DrlxParseUtil.createConstraintCompiler (org.drools.modelcompiler.builder.generator.DrlxParseUtil.createConstraintCompiler)2 TypedExpression (org.drools.modelcompiler.builder.generator.TypedExpression)2 DrlxExpression (org.drools.mvel.parser.ast.expr.DrlxExpression)2 CompiledExpressionResult (org.drools.mvelcompiler.CompiledExpressionResult)2 MvelCompilerContext (org.drools.mvelcompiler.context.MvelCompilerContext)2 BinaryExpr (com.github.javaparser.ast.expr.BinaryExpr)1 EnclosedExpr (com.github.javaparser.ast.expr.EnclosedExpr)1 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)1 NameExpr (com.github.javaparser.ast.expr.NameExpr)1 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)1 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)1 Method (java.lang.reflect.Method)1 BigDecimal (java.math.BigDecimal)1 HashSet (java.util.HashSet)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1