Search in sources :

Example 91 with Expression

use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.

the class RhsParser method processModify.

private ModifyAction processModify(RuleContext context, MethodCallExpr consequenceExpr, MethodCallExpr statement, BlockStmt ruleVariablesBlock) {
    String modifiedId = statement.getArgument(0).toString();
    Class<?> modifiedClass = context.getDeclarationById(modifiedId).orElseThrow(() -> new RuntimeException("Unknown declaration: " + modifiedId)).getDeclarationClass();
    ModifyAction action = new ModifyAction(modifiedClass);
    if (statement.getArguments().size() > 1) {
        String maskId = statement.getArgument(1).toString();
        AssignExpr maskAssignExpr = ruleVariablesBlock.findAll(AssignExpr.class).stream().filter(assign -> ((VariableDeclarationExpr) assign.getTarget()).getVariable(0).toString().equals(maskId)).findFirst().orElseThrow(() -> new RuntimeException("Unknown mask: " + maskId));
        MethodCallExpr maskMethod = ((MethodCallExpr) maskAssignExpr.getValue());
        List<MethodCallExpr> modifyingExprs = consequenceExpr.findAll(MethodCallExpr.class).stream().filter(m -> m.getScope().map(s -> s.toString().equals(modifiedId) || s.toString().equals("(" + modifiedId + ")")).orElse(false)).collect(Collectors.toList());
        for (int i = 1; i < maskMethod.getArguments().size(); i++) {
            String property = maskMethod.getArgument(i).asStringLiteralExpr().asString();
            String setter = "set" + ucFirst(property);
            MethodCallExpr setterExpr = modifyingExprs.stream().filter(m -> m.getNameAsString().equals(setter)).filter(m -> m.getArguments().size() == 1).findFirst().orElse(null);
            Object value = null;
            if (setterExpr != null) {
                Expression arg = setterExpr.getArgument(0);
                arg = stripEnclosedAndCast(arg);
                if (arg.isLiteralExpr()) {
                    value = literalToValue(arg.asLiteralExpr());
                } else if (arg.isNameExpr()) {
                    value = ((ImpactAnalysisRuleContext) context).getBindVariableLiteralMap().get(arg.asNameExpr().getName().asString());
                } else if (arg.isObjectCreationExpr()) {
                    value = objectCreationExprToValue((ObjectCreationExpr) arg, context);
                }
            }
            Method accessor = ClassUtils.getAccessor(modifiedClass, property);
            if (accessor != null && Map.class.isAssignableFrom(accessor.getReturnType())) {
                String mapName = property;
                List<MethodCallExpr> mapPutExprs = consequenceExpr.findAll(MethodCallExpr.class).stream().filter(m -> isMapPutExpr(m, modifiedId, accessor.getName())).collect(Collectors.toList());
                mapPutExprs.stream().forEach(expr -> {
                    String mapKey = getLiteralString(context, expr.getArgument(0));
                    Object mapValue = getLiteralValue(context, expr.getArgument(1));
                    action.addModifiedProperty(new ModifiedMapProperty(mapName, mapKey, mapValue));
                });
            } else {
                action.addModifiedProperty(new ModifiedProperty(property, value));
            }
        }
    }
    return action;
}
Also used : ParserUtil.getLiteralString(org.drools.impact.analysis.parser.impl.ParserUtil.getLiteralString) RuleDescr(org.drools.drl.ast.descr.RuleDescr) ParserUtil.literalToValue(org.drools.impact.analysis.parser.impl.ParserUtil.literalToValue) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) InsertedProperty(org.drools.impact.analysis.model.right.InsertedProperty) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) ParserUtil.isLiteral(org.drools.impact.analysis.parser.impl.ParserUtil.isLiteral) ModifiedProperty(org.drools.impact.analysis.model.right.ModifiedProperty) Rule(org.drools.impact.analysis.model.Rule) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ParserUtil.getLiteralValue(org.drools.impact.analysis.parser.impl.ParserUtil.getLiteralValue) ParserUtil.literalType(org.drools.impact.analysis.parser.impl.ParserUtil.literalType) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) ParserUtil.objectCreationExprToValue(org.drools.impact.analysis.parser.impl.ParserUtil.objectCreationExprToValue) Method(java.lang.reflect.Method) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) ParserUtil.stripEnclosedAndCast(org.drools.impact.analysis.parser.impl.ParserUtil.stripEnclosedAndCast) ClassUtils(org.drools.core.util.ClassUtils) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) StringUtils.ucFirst(org.drools.core.util.StringUtils.ucFirst) ModifiedMapProperty(org.drools.impact.analysis.model.right.ModifiedMapProperty) Collectors(java.util.stream.Collectors) ModifyAction(org.drools.impact.analysis.model.right.ModifyAction) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) Objects(java.util.Objects) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) List(java.util.List) InsertAction(org.drools.impact.analysis.model.right.InsertAction) Consequence(org.drools.modelcompiler.builder.generator.Consequence) Optional(java.util.Optional) ConsequenceAction(org.drools.impact.analysis.model.right.ConsequenceAction) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ModifyAction(org.drools.impact.analysis.model.right.ModifyAction) ParserUtil.getLiteralString(org.drools.impact.analysis.parser.impl.ParserUtil.getLiteralString) Method(java.lang.reflect.Method) ModifiedProperty(org.drools.impact.analysis.model.right.ModifiedProperty) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) Expression(com.github.javaparser.ast.expr.Expression) ModifiedMapProperty(org.drools.impact.analysis.model.right.ModifiedMapProperty) Map(java.util.Map) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 92 with Expression

use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.

the class LhsParser method processMapProperty.

private Constraint processMapProperty(RuleContext context, Constraint constraint, TypedExpression expr) {
    MethodCallExpr mce = expr.getExpression().asMethodCallExpr();
    Optional<Expression> scope = mce.getScope();
    if (scope.isPresent() && scope.get().isMethodCallExpr()) {
        MethodCallExpr scopeMce = scope.get().asMethodCallExpr();
        String prop = ClassUtils.getter2property(scopeMce.getName().asString());
        Optional<Class<?>> origType = expr.getOriginalPatternType();
        if (prop != null && origType.isPresent()) {
            Method accessor = ClassUtils.getAccessor(origType.get(), prop);
            if (accessor != null && Map.class.isAssignableFrom(accessor.getReturnType()) && mce.getName().asString().equals("get")) {
                String key = getLiteralString(context, mce.getArgument(0));
                if (key != null) {
                    MapConstraint mapConstraint = new MapConstraint(constraint);
                    // map name
                    mapConstraint.setProperty(prop);
                    mapConstraint.setKey(key);
                    constraint = mapConstraint;
                }
            }
        }
    }
    return constraint;
}
Also used : ConstraintExpression(org.drools.modelcompiler.builder.generator.drlxparse.ConstraintExpression) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) MapConstraint(org.drools.impact.analysis.model.left.MapConstraint) ParserUtil.getLiteralString(org.drools.impact.analysis.parser.impl.ParserUtil.getLiteralString) Method(java.lang.reflect.Method) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 93 with Expression

use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.

the class LhsParser method parseExpressionInConstraint.

private Constraint parseExpressionInConstraint(RuleContext context, Constraint constraint, TypedExpression expr) {
    Expression expression = expr.getExpression();
    expression = stripEnclosedAndCast(expression);
    if (expression.isMethodCallExpr()) {
        if (isThisExpression(expression.asMethodCallExpr().getScope().orElse(null))) {
            constraint.setProperty(expr.getFieldName());
        } else {
            constraint = processMapProperty(context, constraint, expr);
        }
    } else if (expression.isLiteralExpr()) {
        constraint.setValue(literalToValue(expression.asLiteralExpr()));
    } else if (expression.isNameExpr() && expression.asNameExpr().getNameAsString().equals("_this")) {
        constraint.setProperty("this");
    } else if (expression.isObjectCreationExpr()) {
        constraint.setValue(objectCreationExprToValue(expression.asObjectCreationExpr(), context));
    }
    return constraint;
}
Also used : ConstraintExpression(org.drools.modelcompiler.builder.generator.drlxparse.ConstraintExpression) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression)

Example 94 with Expression

use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.

the class CoercedExpression method coerce.

public CoercedExpressionResult coerce() {
    final Class<?> leftClass = left.getRawClass();
    final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
    final Class<?> rightClass = right.getRawClass();
    final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
    boolean sameClass = leftClass == rightClass;
    boolean isUnificationExpression = left instanceof UnificationTypedExpression || right instanceof UnificationTypedExpression;
    if (sameClass || isUnificationExpression) {
        return new CoercedExpressionResult(left, right);
    }
    if (!canCoerce()) {
        throw new CoercedExpressionException(new InvalidExpressionErrorResult("Comparison operation requires compatible types. Found " + leftClass + " and " + rightClass));
    }
    if ((nonPrimitiveLeftClass == Integer.class || nonPrimitiveLeftClass == Long.class) && nonPrimitiveRightClass == Double.class) {
        CastExpr castExpression = new CastExpr(PrimitiveType.doubleType(), this.left.getExpression());
        return new CoercedExpressionResult(new TypedExpression(castExpression, double.class, left.getType()), right, false);
    }
    final boolean leftIsPrimitive = leftClass.isPrimitive() || Number.class.isAssignableFrom(leftClass);
    final boolean canCoerceLiteralNumberExpr = canCoerceLiteralNumberExpr(leftClass);
    boolean rightAsStaticField = false;
    final Expression rightExpression = right.getExpression();
    final TypedExpression coercedRight;
    if (leftIsPrimitive && canCoerceLiteralNumberExpr && rightExpression instanceof LiteralStringValueExpr) {
        final Expression coercedLiteralNumberExprToType = coerceLiteralNumberExprToType((LiteralStringValueExpr) right.getExpression(), leftClass);
        coercedRight = right.cloneWithNewExpression(coercedLiteralNumberExprToType);
        coercedRight.setType(leftClass);
    } else if (shouldCoerceBToString(left, right)) {
        coercedRight = coerceToString(right);
    } else if (isNotBinaryExpression(right) && canBeNarrowed(leftClass, rightClass) && right.isNumberLiteral()) {
        coercedRight = castToClass(leftClass);
    } else if (leftClass == long.class && rightClass == int.class) {
        coercedRight = right.cloneWithNewExpression(new CastExpr(PrimitiveType.longType(), right.getExpression()));
    } else if (leftClass == Date.class && rightClass == String.class) {
        coercedRight = coerceToDate(right);
        rightAsStaticField = true;
    } else if (leftClass == LocalDate.class && rightClass == String.class) {
        coercedRight = coerceToLocalDate(right);
        rightAsStaticField = true;
    } else if (leftClass == LocalDateTime.class && rightClass == String.class) {
        coercedRight = coerceToLocalDateTime(right);
        rightAsStaticField = true;
    } else if (shouldCoerceBToMap()) {
        coercedRight = castToClass(toNonPrimitiveType(leftClass));
    } else if (isBoolean(leftClass) && !isBoolean(rightClass)) {
        coercedRight = coerceBoolean(right);
    } else {
        coercedRight = right;
    }
    final TypedExpression coercedLeft;
    if (nonPrimitiveLeftClass == Character.class && shouldCoerceBToString(right, left)) {
        coercedLeft = coerceToString(left);
    } else {
        coercedLeft = left;
    }
    return new CoercedExpressionResult(coercedLeft, coercedRight, rightAsStaticField);
}
Also used : LocalDateTime(java.time.LocalDateTime) LiteralStringValueExpr(com.github.javaparser.ast.expr.LiteralStringValueExpr) Date(java.util.Date) LocalDate(java.time.LocalDate) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) Expression(com.github.javaparser.ast.expr.Expression) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) CastExpr(com.github.javaparser.ast.expr.CastExpr) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression)

Example 95 with Expression

use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.

the class ConstraintParser method handleSpecialComparisonCases.

private SpecialComparisonResult handleSpecialComparisonCases(ExpressionTyper expressionTyper, BinaryExpr.Operator operator, TypedExpression left, TypedExpression right) {
    if (isLogicalOperator(operator)) {
        Expression rewrittenLeft = handleSpecialComparisonCases(expressionTyper, left);
        Expression rewrittenRight = handleSpecialComparisonCases(expressionTyper, right);
        if (rewrittenLeft != null && rewrittenRight != null) {
            return new SpecialComparisonResult(new BinaryExpr(rewrittenLeft, rewrittenRight, operator), left, right);
        }
    }
    boolean comparison = isComparisonOperator(operator);
    if ((isAnyOperandBigDecimal(left, right) || isAnyOperandBigInteger(left, right)) && comparison) {
        return compareBigDecimal(operator, left, right);
    }
    if (comparison) {
        SpecialComparisonCase methodName = specialComparisonFactory(left, right);
        return methodName.createCompareMethod(operator);
    }
    return new SpecialComparisonResult(new BinaryExpr(left.getExpression(), right.getExpression(), operator), left, right);
}
Also used : Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) DrlxExpression(org.drools.mvel.parser.ast.expr.DrlxExpression) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) HalfBinaryExpr(org.drools.mvel.parser.ast.expr.HalfBinaryExpr)

Aggregations

Expression (com.github.javaparser.ast.expr.Expression)429 Test (org.junit.Test)166 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)149 NameExpr (com.github.javaparser.ast.expr.NameExpr)135 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)94 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)90 DrlxExpression (org.drools.mvel.parser.ast.expr.DrlxExpression)84 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)73 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)71 NodeList (com.github.javaparser.ast.NodeList)66 DrlxParser.parseExpression (org.drools.mvel.parser.DrlxParser.parseExpression)61 TypedExpression (org.drools.modelcompiler.builder.generator.TypedExpression)53 CompilationUnit (com.github.javaparser.ast.CompilationUnit)51 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)50 BinaryExpr (com.github.javaparser.ast.expr.BinaryExpr)49 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)49 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)46 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)44 List (java.util.List)44 ExpressionStmt (com.github.javaparser.ast.stmt.ExpressionStmt)43