Search in sources :

Example 21 with Expression

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

the class DrlxParseUtilTest method throwExceptionWhenMissingNode.

@Test(expected = UnsupportedOperationException.class)
public void throwExceptionWhenMissingNode() {
    final Expression expr = JavaParser.parseExpression("this");
    DrlxParseUtil.prepend(null, expr);
}
Also used : Expression(org.drools.javaparser.ast.expr.Expression) Test(org.junit.Test)

Example 22 with Expression

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

the class DrlxParseUtilTest method transformMethodExpressionToMethodCallExpressionTypeSafe.

@Test
public void transformMethodExpressionToMethodCallExpressionTypeSafe() {
    final Expression expr = JavaParser.parseExpression("address.city.startsWith(\"M\")");
    final Expression expr1 = JavaParser.parseExpression("getAddress().city.startsWith(\"M\")");
    final Expression expr2 = JavaParser.parseExpression("address.getCity().startsWith(\"M\")");
    final MethodCallExpr expected = JavaParser.parseExpression("getAddress().getCity().startsWith(\"M\")");
    assertEquals(expected.toString(), DrlxParseUtil.toMethodCallWithClassCheck(null, expr, null, Person.class, typeResolver).getExpression().toString());
    assertEquals(expected.toString(), DrlxParseUtil.toMethodCallWithClassCheck(null, expr1, null, Person.class, typeResolver).getExpression().toString());
    assertEquals(expected.toString(), DrlxParseUtil.toMethodCallWithClassCheck(null, expr2, null, Person.class, typeResolver).getExpression().toString());
}
Also used : Expression(org.drools.javaparser.ast.expr.Expression) Person(org.drools.modelcompiler.domain.Person) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) Test(org.junit.Test)

Example 23 with Expression

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

the class Consequence method rewriteConsequenceBlock.

private String rewriteConsequenceBlock(String consequence) {
    int modifyPos = StringUtils.indexOfOutOfQuotes(consequence, "modify");
    if (modifyPos < 0) {
        return consequence;
    }
    int lastCopiedEnd = 0;
    StringBuilder sb = new StringBuilder();
    sb.append(consequence.substring(lastCopiedEnd, modifyPos));
    lastCopiedEnd = modifyPos + 1;
    for (; modifyPos >= 0; modifyPos = StringUtils.indexOfOutOfQuotes(consequence, "modify", modifyPos + 6)) {
        int declStart = consequence.indexOf('(', modifyPos + 6);
        int declEnd = consequence.indexOf(')', declStart + 1);
        if (declEnd < 0) {
            continue;
        }
        String decl = consequence.substring(declStart + 1, declEnd).trim();
        if (!context.getDeclarationById(decl).isPresent()) {
            continue;
        }
        int blockStart = consequence.indexOf('{', declEnd + 1);
        int blockEnd = consequence.indexOf('}', blockStart + 1);
        if (blockEnd < 0) {
            continue;
        }
        if (lastCopiedEnd < modifyPos) {
            sb.append(consequence.substring(lastCopiedEnd, modifyPos));
        }
        NameExpr declAsNameExpr = new NameExpr(decl);
        String originalBlock = consequence.substring(blockStart + 1, blockEnd).trim();
        BlockStmt modifyBlock = JavaParser.parseBlock("{" + originalBlock + ";}");
        List<MethodCallExpr> originalMethodCalls = modifyBlock.findAll(MethodCallExpr.class);
        for (MethodCallExpr mc : originalMethodCalls) {
            Expression mcWithScope = org.drools.modelcompiler.builder.generator.DrlxParseUtil.prepend(declAsNameExpr, mc);
            modifyBlock.replace(mc, mcWithScope);
        }
        for (Statement n : modifyBlock.getStatements()) {
            if (!(n instanceof EmptyStmt)) {
                sb.append(n);
            }
        }
        sb.append("update(").append(decl).append(");\n");
        lastCopiedEnd = blockEnd + 1;
    }
    if (lastCopiedEnd < consequence.length()) {
        sb.append(consequence.substring(lastCopiedEnd));
    }
    return sb.toString();
}
Also used : Expression(org.drools.javaparser.ast.expr.Expression) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) Statement(org.drools.javaparser.ast.stmt.Statement) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) NameExpr(org.drools.javaparser.ast.expr.NameExpr) EmptyStmt(org.drools.javaparser.ast.stmt.EmptyStmt) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 24 with Expression

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

the class Consequence method rewriteRHS.

private boolean rewriteRHS(BlockStmt ruleBlock, BlockStmt rhs) {
    AtomicBoolean requireDrools = new AtomicBoolean(false);
    List<MethodCallExpr> methodCallExprs = rhs.findAll(MethodCallExpr.class);
    List<MethodCallExpr> updateExprs = new ArrayList<>();
    for (MethodCallExpr methodCallExpr : methodCallExprs) {
        if (isDroolsMethod(methodCallExpr)) {
            if (!methodCallExpr.getScope().isPresent()) {
                methodCallExpr.setScope(new NameExpr("drools"));
            }
            if (knowledgeHelperMethods.contains(methodCallExpr.getNameAsString())) {
                methodCallExpr.setScope(asKnoledgeHelperExpression);
            } else if (methodCallExpr.getNameAsString().equals("update")) {
                updateExprs.add(methodCallExpr);
            } else if (methodCallExpr.getNameAsString().equals("retract")) {
                methodCallExpr.setName(new SimpleName("delete"));
            }
            requireDrools.set(true);
        }
    }
    for (MethodCallExpr updateExpr : updateExprs) {
        Expression argExpr = updateExpr.getArgument(0);
        if (argExpr instanceof NameExpr) {
            String updatedVar = ((NameExpr) argExpr).getNameAsString();
            Class<?> updatedClass = context.getDeclarationById(updatedVar).map(DeclarationSpec::getDeclarationClass).orElseThrow(RuntimeException::new);
            MethodCallExpr bitMaskCreation = new MethodCallExpr(new NameExpr(BitMask.class.getCanonicalName()), "getPatternMask");
            bitMaskCreation.addArgument(new ClassExpr(JavaParser.parseClassOrInterfaceType(updatedClass.getCanonicalName())));
            methodCallExprs.subList(0, methodCallExprs.indexOf(updateExpr)).stream().filter(mce -> mce.getScope().isPresent() && hasScope(mce, updatedVar)).map(mce -> ClassUtils.setter2property(mce.getNameAsString())).filter(Objects::nonNull).distinct().forEach(s -> bitMaskCreation.addArgument(new StringLiteralExpr(s)));
            VariableDeclarationExpr bitMaskVar = new VariableDeclarationExpr(BITMASK_TYPE, "mask_" + updatedVar, Modifier.FINAL);
            AssignExpr bitMaskAssign = new AssignExpr(bitMaskVar, bitMaskCreation, AssignExpr.Operator.ASSIGN);
            ruleBlock.addStatement(bitMaskAssign);
            updateExpr.addArgument("mask_" + updatedVar);
        }
    }
    return requireDrools.get();
}
Also used : BitMask(org.drools.model.BitMask) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) Expression(org.drools.javaparser.ast.expr.Expression) DrlxParseUtil.isNameExprWithName(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isNameExprWithName) DroolsImpl(org.drools.modelcompiler.consequence.DroolsImpl) JavaParser(org.drools.javaparser.JavaParser) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) BREAKING_CALL(org.drools.modelcompiler.builder.generator.visitor.NamedConsequenceVisitor.BREAKING_CALL) LambdaExpr(org.drools.javaparser.ast.expr.LambdaExpr) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) Statement(org.drools.javaparser.ast.stmt.Statement) Collectors.toSet(java.util.stream.Collectors.toSet) PackageModel(org.drools.modelcompiler.builder.PackageModel) ObjectCreationExpr(org.drools.javaparser.ast.expr.ObjectCreationExpr) DrlxParseUtil.hasScope(org.drools.modelcompiler.builder.generator.DrlxParseUtil.hasScope) Parameter(org.drools.javaparser.ast.body.Parameter) ClassUtils(org.drools.core.util.ClassUtils) Collection(java.util.Collection) DrlxParseUtil.parseBlock(org.drools.modelcompiler.builder.generator.DrlxParseUtil.parseBlock) Set(java.util.Set) EmptyStmt(org.drools.javaparser.ast.stmt.EmptyStmt) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) Objects(java.util.Objects) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) UnknownType(org.drools.javaparser.ast.type.UnknownType) DrlxParseUtil.findAllChildrenRecursive(org.drools.modelcompiler.builder.generator.DrlxParseUtil.findAllChildrenRecursive) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Modifier(org.drools.javaparser.ast.Modifier) SimpleName(org.drools.javaparser.ast.expr.SimpleName) StringUtils(org.drools.core.util.StringUtils) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) SimpleName(org.drools.javaparser.ast.expr.SimpleName) ArrayList(java.util.ArrayList) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Expression(org.drools.javaparser.ast.expr.Expression) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) Objects(java.util.Objects) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 25 with Expression

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

the class DrlxParseUtil method toMethodCallWithClassCheck.

public static TypedExpression toMethodCallWithClassCheck(RuleContext context, Expression expr, String bindingId, Class<?> clazz, TypeResolver typeResolver) {
    final Deque<ParsedMethod> callStackLeftToRight = new LinkedList<>();
    createExpressionCall(expr, callStackLeftToRight);
    Class<?> previousClass = clazz;
    Expression previousScope = null;
    for (ParsedMethod e : callStackLeftToRight) {
        if (e.expression instanceof NameExpr || e.expression instanceof FieldAccessExpr) {
            if (e.fieldToResolve.equals(bindingId)) {
                continue;
            }
            if (previousClass == null) {
                try {
                    previousClass = typeResolver.resolveType(e.fieldToResolve);
                    previousScope = new NameExpr(e.fieldToResolve);
                } catch (ClassNotFoundException e1) {
                // ignore
                }
                if (previousClass == null) {
                    previousClass = context.getDeclarationById(e.fieldToResolve).map(DeclarationSpec::getDeclarationClass).orElseThrow(() -> new RuntimeException("Unknown field: " + e.fieldToResolve));
                    previousScope = e.expression;
                }
            } else {
                TypedExpression te = nameExprToMethodCallExpr(e.fieldToResolve, previousClass, previousScope);
                Class<?> returnType = te.getType();
                previousScope = te.getExpression();
                previousClass = returnType;
            }
        } else if (e.expression instanceof MethodCallExpr) {
            Class<?> returnType = returnTypeOfMethodCallExpr(context, typeResolver, (MethodCallExpr) e.expression, previousClass, null);
            MethodCallExpr cloned = ((MethodCallExpr) e.expression.clone()).setScope(previousScope);
            previousScope = cloned;
            previousClass = returnType;
        }
    }
    return new TypedExpression(previousScope, previousClass);
}
Also used : ExpressionTyper.findLeftLeafOfNameExpr(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyper.findLeftLeafOfNameExpr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) LinkedList(java.util.LinkedList) Expression(org.drools.javaparser.ast.expr.Expression) DrlxExpression(org.drools.javaparser.ast.drlx.expr.DrlxExpression) FieldAccessExpr(org.drools.javaparser.ast.expr.FieldAccessExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Aggregations

Expression (org.drools.javaparser.ast.expr.Expression)48 MethodCallExpr (org.drools.javaparser.ast.expr.MethodCallExpr)32 NameExpr (org.drools.javaparser.ast.expr.NameExpr)25 TypedExpression (org.drools.modelcompiler.builder.generator.TypedExpression)19 List (java.util.List)14 ArrayList (java.util.ArrayList)13 Optional (java.util.Optional)13 FieldAccessExpr (org.drools.javaparser.ast.expr.FieldAccessExpr)13 BinaryExpr (org.drools.javaparser.ast.expr.BinaryExpr)11 EnclosedExpr (org.drools.javaparser.ast.expr.EnclosedExpr)11 PackageModel (org.drools.modelcompiler.builder.PackageModel)11 RuleContext (org.drools.modelcompiler.builder.generator.RuleContext)11 Node (org.drools.javaparser.ast.Node)10 StringLiteralExpr (org.drools.javaparser.ast.expr.StringLiteralExpr)10 Collection (java.util.Collection)9 Parameter (org.drools.javaparser.ast.body.Parameter)9 LambdaExpr (org.drools.javaparser.ast.expr.LambdaExpr)9 DeclarationSpec (org.drools.modelcompiler.builder.generator.DeclarationSpec)9 DrlxParseUtil.toVar (org.drools.modelcompiler.builder.generator.DrlxParseUtil.toVar)8 JavaParser (org.drools.javaparser.JavaParser)7