Search in sources :

Example 6 with ThisExpr

use of com.github.javaparser.ast.expr.ThisExpr in project javaparser by javaparser.

the class MethodsResolutionTest method thisInAnonymousClass.

@Test
public void thisInAnonymousClass() {
    CompilationUnit cu = parseSample("ThisInAnonymousClass");
    ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Bar");
    ThisExpr thisExpression = Navigator.findNodeOfGivenClass(clazz, ThisExpr.class);
    ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(thisExpression);
    assertEquals(true, type.isReferenceType());
    assertEquals(true, type.asReferenceType().getTypeDeclaration() instanceof JavaParserAnonymousClassDeclaration);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) JavaParserAnonymousClassDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserAnonymousClassDeclaration) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) Test(org.junit.Test)

Example 7 with ThisExpr

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

the class ExpressionTyper method processFirstNode.

private Optional<TypedExpressionCursor> processFirstNode(Expression drlxExpr, List<Node> childNodes, Node firstNode, boolean isInLineCast, java.lang.reflect.Type originalTypeCursor) {
    Optional<TypedExpressionCursor> result;
    if (isThisExpression(firstNode) || (firstNode instanceof DrlNameExpr && printNode(firstNode).equals(bindingId))) {
        result = of(thisExpr(drlxExpr, childNodes, isInLineCast, originalTypeCursor));
    } else if (firstNode instanceof DrlNameExpr) {
        result = drlNameExpr(drlxExpr, (DrlNameExpr) firstNode, isInLineCast, originalTypeCursor);
    } else if (firstNode instanceof NameExpr) {
        result = drlNameExpr(drlxExpr, new DrlNameExpr(((NameExpr) firstNode).getName()), isInLineCast, originalTypeCursor);
    } else if (firstNode instanceof FieldAccessExpr) {
        if (((FieldAccessExpr) firstNode).getScope() instanceof ThisExpr) {
            result = of(fieldAccessExpr(originalTypeCursor, ((FieldAccessExpr) firstNode).getName()));
        } else {
            try {
                Class<?> resolvedType = ruleContext.getTypeResolver().resolveType(PrintUtil.printNode(firstNode));
                result = of(new TypedExpressionCursor(new NameExpr(PrintUtil.printNode(firstNode)), resolvedType));
            } catch (ClassNotFoundException e) {
                result = empty();
            }
        }
    } else if (firstNode instanceof NullSafeFieldAccessExpr && ((NullSafeFieldAccessExpr) firstNode).getScope() instanceof ThisExpr) {
        result = of(fieldAccessExpr(originalTypeCursor, ((NullSafeFieldAccessExpr) firstNode).getName()));
    } else if (firstNode instanceof MethodCallExpr) {
        Optional<Expression> scopeExpr = ((MethodCallExpr) firstNode).getScope();
        Optional<DeclarationSpec> scopeDecl = scopeExpr.flatMap(scope -> ruleContext.getDeclarationById(PrintUtil.printNode(scope)));
        Expression scope;
        java.lang.reflect.Type type;
        if (scopeDecl.isPresent() && !scopeDecl.get().getBindingId().equals(bindingId)) {
            type = scopeDecl.get().getDeclarationClass();
            scope = new NameExpr(scopeDecl.get().getBindingId());
            context.addUsedDeclarations(scopeDecl.get().getBindingId());
        } else if (scopeExpr.isPresent()) {
            TypedExpressionCursor parsedScope = processFirstNode(drlxExpr, childNodes, scopeExpr.get(), isInLineCast, originalTypeCursor).get();
            type = parsedScope.typeCursor;
            scope = parsedScope.expressionCursor;
        } else {
            type = originalTypeCursor;
            scope = new NameExpr(THIS_PLACEHOLDER);
        }
        result = of(methodCallExpr((MethodCallExpr) firstNode, type, scope));
    } else if (firstNode instanceof ObjectCreationExpr) {
        result = of(objectCreationExpr((ObjectCreationExpr) firstNode));
    } else if (firstNode instanceof StringLiteralExpr) {
        result = of(stringLiteralExpr((StringLiteralExpr) firstNode));
    } else if (firstNode instanceof EnclosedExpr) {
        result = processFirstNode(drlxExpr, childNodes, ((EnclosedExpr) firstNode).getInner(), isInLineCast, originalTypeCursor);
    } else if (firstNode instanceof CastExpr) {
        result = castExpr((CastExpr) firstNode, drlxExpr, childNodes, isInLineCast, originalTypeCursor);
    } else if (firstNode instanceof ArrayCreationExpr) {
        result = of(arrayCreationExpr(((ArrayCreationExpr) firstNode)));
    } else if (firstNode instanceof BinaryExpr) {
        result = of(binaryExpr((BinaryExpr) firstNode));
    } else if (firstNode instanceof ArrayAccessExpr) {
        Optional<DeclarationSpec> scopeDecl = ruleContext.getDeclarationById(((ArrayAccessExpr) firstNode).getName().toString());
        Expression scope;
        java.lang.reflect.Type type;
        if (scopeDecl.isPresent() && !scopeDecl.get().getBindingId().equals(bindingId)) {
            type = scopeDecl.get().getDeclarationClass();
            scope = new NameExpr(scopeDecl.get().getBindingId());
            context.addUsedDeclarations(scopeDecl.get().getBindingId());
        } else {
            type = originalTypeCursor;
            scope = new NameExpr(THIS_PLACEHOLDER);
        }
        result = arrayAccessExpr((ArrayAccessExpr) firstNode, type, scope);
    } else if (firstNode instanceof MapCreationLiteralExpression) {
        result = mapCreationLiteral((MapCreationLiteralExpression) firstNode, originalTypeCursor);
    } else if (firstNode instanceof ListCreationLiteralExpression) {
        result = listCreationLiteral((ListCreationLiteralExpression) firstNode, originalTypeCursor);
    } else {
        result = of(new TypedExpressionCursor((Expression) firstNode, getExpressionType(ruleContext, ruleContext.getTypeResolver(), (Expression) firstNode, context.getUsedDeclarations())));
    }
    if (result.isPresent()) {
        processNullSafeDereferencing(drlxExpr);
    }
    return result.map(te -> {
        if (isInLineCast) {
            Expression exprWithInlineCast = addCastToExpression(toRawClass(te.typeCursor), te.expressionCursor, isInLineCast);
            return new TypedExpressionCursor(exprWithInlineCast, te.typeCursor);
        } else {
            return te;
        }
    });
}
Also used : ArrayAccessExpr(com.github.javaparser.ast.expr.ArrayAccessExpr) Arrays(java.util.Arrays) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) HalfPointFreeExpr(org.drools.mvel.parser.ast.expr.HalfPointFreeExpr) DrlxParseUtil.findRootNodeViaParent(org.drools.modelcompiler.builder.generator.DrlxParseUtil.findRootNodeViaParent) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) NodeList.nodeList(com.github.javaparser.ast.NodeList.nodeList) Optional.of(java.util.Optional.of) InstanceOfExpr(com.github.javaparser.ast.expr.InstanceOfExpr) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) ParseExpressionErrorResult(org.drools.modelcompiler.builder.errors.ParseExpressionErrorResult) FlattenScope.flattenScope(org.drools.modelcompiler.builder.generator.expressiontyper.FlattenScope.flattenScope) LiteralExpr(com.github.javaparser.ast.expr.LiteralExpr) CharLiteralExpr(com.github.javaparser.ast.expr.CharLiteralExpr) Type(com.github.javaparser.ast.type.Type) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) FlattenScope.transformFullyQualifiedInlineCastExpr(org.drools.modelcompiler.builder.generator.expressiontyper.FlattenScope.transformFullyQualifiedInlineCastExpr) ClassUtil.toRawClass(org.drools.modelcompiler.util.ClassUtil.toRawClass) DrlxParseUtil.getClassFromContext(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getClassFromContext) OperatorSpec(org.drools.modelcompiler.builder.generator.operatorspec.OperatorSpec) OOPathExpr(org.drools.mvel.parser.ast.expr.OOPathExpr) PackageModel(org.drools.modelcompiler.builder.PackageModel) SimpleName(com.github.javaparser.ast.expr.SimpleName) ArrayCreationExpr(com.github.javaparser.ast.expr.ArrayCreationExpr) DrlxParseUtil.getExpressionType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getExpressionType) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) MapCreationLiteralExpressionKeyValuePair(org.drools.mvel.parser.ast.expr.MapCreationLiteralExpressionKeyValuePair) MethodUtils(org.drools.core.util.MethodUtils) UnaryExpr(com.github.javaparser.ast.expr.UnaryExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ArrayInitializerExpr(com.github.javaparser.ast.expr.ArrayInitializerExpr) Optional.empty(java.util.Optional.empty) DrlxParseUtil.replaceAllHalfBinaryChildren(org.drools.modelcompiler.builder.generator.DrlxParseUtil.replaceAllHalfBinaryChildren) PrintUtil.printNode(org.drools.mvel.parser.printer.PrintUtil.printNode) CastExpr(com.github.javaparser.ast.expr.CastExpr) ArrayList(java.util.ArrayList) NullSafeMethodCallExpr(org.drools.mvel.parser.ast.expr.NullSafeMethodCallExpr) DrlxParseUtil.transformDrlNameExprToNameExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.transformDrlNameExprToNameExpr) ListCreationLiteralExpressionElement(org.drools.mvel.parser.ast.expr.ListCreationLiteralExpressionElement) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) TypeVariable(java.lang.reflect.TypeVariable) NativeOperatorSpec(org.drools.modelcompiler.builder.generator.operatorspec.NativeOperatorSpec) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) InlineCastExpr(org.drools.mvel.parser.ast.expr.InlineCastExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) Field(java.lang.reflect.Field) InitializerDeclaration(com.github.javaparser.ast.body.InitializerDeclaration) ParameterizedType(java.lang.reflect.ParameterizedType) ModelGenerator(org.drools.modelcompiler.builder.generator.ModelGenerator) MapCreationLiteralExpression(org.drools.mvel.parser.ast.expr.MapCreationLiteralExpression) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) DrlxParseUtil.prepend(org.drools.modelcompiler.builder.generator.DrlxParseUtil.prepend) DrlxParseUtil.getClassFromType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getClassFromType) TypeResolver(org.drools.core.addon.TypeResolver) TemporalOperatorSpec(org.drools.modelcompiler.builder.generator.operatorspec.TemporalOperatorSpec) LoggerFactory(org.slf4j.LoggerFactory) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) ClassUtils.getter2property(org.drools.core.util.ClassUtils.getter2property) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) CustomOperatorSpec(org.drools.modelcompiler.builder.generator.operatorspec.CustomOperatorSpec) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) Method(java.lang.reflect.Method) Node(com.github.javaparser.ast.Node) NodeList(com.github.javaparser.ast.NodeList) ReferenceType(com.github.javaparser.ast.type.ReferenceType) HalfBinaryExpr(org.drools.mvel.parser.ast.expr.HalfBinaryExpr) ListCreationLiteralExpression(org.drools.mvel.parser.ast.expr.ListCreationLiteralExpression) OOPathChunk(org.drools.mvel.parser.ast.expr.OOPathChunk) FullyQualifiedInlineCastExpr(org.drools.mvel.parser.ast.expr.FullyQualifiedInlineCastExpr) DrlxParseUtil.safeResolveType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.safeResolveType) THIS_PLACEHOLDER(org.drools.modelcompiler.builder.generator.DrlxParseUtil.THIS_PLACEHOLDER) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) List(java.util.List) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) DrlxParseUtil.nameExprToMethodCallExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.nameExprToMethodCallExpr) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) MvelParser.parseType(org.drools.mvel.parser.MvelParser.parseType) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) DrlxParseUtil.toStringLiteral(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toStringLiteral) NodeWithArguments(com.github.javaparser.ast.nodeTypes.NodeWithArguments) HashMap(java.util.HashMap) ClassUtils.extractGenericType(org.drools.core.util.ClassUtils.extractGenericType) PointFreeExpr(org.drools.mvel.parser.ast.expr.PointFreeExpr) DoubleLiteralExpr(com.github.javaparser.ast.expr.DoubleLiteralExpr) DrlxParseUtil.getLiteralExpressionType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getLiteralExpressionType) ClassUtil.getTypeArgument(org.drools.modelcompiler.util.ClassUtil.getTypeArgument) RuleUnitUtil.isDataSource(org.kie.internal.ruleunit.RuleUnitUtil.isDataSource) NoSuchElementException(java.util.NoSuchElementException) Logger(org.slf4j.Logger) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) NullSafeFieldAccessExpr(org.drools.mvel.parser.ast.expr.NullSafeFieldAccessExpr) PrintUtil(org.drools.mvel.parser.printer.PrintUtil) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) DrlxParseUtil.trasformHalfBinaryToBinary(org.drools.modelcompiler.builder.generator.DrlxParseUtil.trasformHalfBinaryToBinary) BigDecimalArgumentCoercion(org.drools.mvelcompiler.util.BigDecimalArgumentCoercion) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) DrlxParseUtil.transformDrlNameExprToNameExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.transformDrlNameExprToNameExpr) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) FlattenScope.transformFullyQualifiedInlineCastExpr(org.drools.modelcompiler.builder.generator.expressiontyper.FlattenScope.transformFullyQualifiedInlineCastExpr) CastExpr(com.github.javaparser.ast.expr.CastExpr) InlineCastExpr(org.drools.mvel.parser.ast.expr.InlineCastExpr) FullyQualifiedInlineCastExpr(org.drools.mvel.parser.ast.expr.FullyQualifiedInlineCastExpr) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) NullSafeFieldAccessExpr(org.drools.mvel.parser.ast.expr.NullSafeFieldAccessExpr) ArrayCreationExpr(com.github.javaparser.ast.expr.ArrayCreationExpr) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) ListCreationLiteralExpression(org.drools.mvel.parser.ast.expr.ListCreationLiteralExpression) Optional(java.util.Optional) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) ArrayAccessExpr(com.github.javaparser.ast.expr.ArrayAccessExpr) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) HalfBinaryExpr(org.drools.mvel.parser.ast.expr.HalfBinaryExpr) NullSafeFieldAccessExpr(org.drools.mvel.parser.ast.expr.NullSafeFieldAccessExpr) MapCreationLiteralExpression(org.drools.mvel.parser.ast.expr.MapCreationLiteralExpression) Type(com.github.javaparser.ast.type.Type) DrlxParseUtil.getExpressionType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getExpressionType) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) ParameterizedType(java.lang.reflect.ParameterizedType) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) DrlxParseUtil.getClassFromType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getClassFromType) ReferenceType(com.github.javaparser.ast.type.ReferenceType) DrlxParseUtil.safeResolveType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.safeResolveType) MvelParser.parseType(org.drools.mvel.parser.MvelParser.parseType) ClassUtils.extractGenericType(org.drools.core.util.ClassUtils.extractGenericType) DrlxParseUtil.getLiteralExpressionType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getLiteralExpressionType) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) Expression(com.github.javaparser.ast.expr.Expression) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) MapCreationLiteralExpression(org.drools.mvel.parser.ast.expr.MapCreationLiteralExpression) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) ListCreationLiteralExpression(org.drools.mvel.parser.ast.expr.ListCreationLiteralExpression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) ClassUtil.toRawClass(org.drools.modelcompiler.util.ClassUtil.toRawClass) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) NullSafeMethodCallExpr(org.drools.mvel.parser.ast.expr.NullSafeMethodCallExpr) DrlxParseUtil.nameExprToMethodCallExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.nameExprToMethodCallExpr)

Example 8 with ThisExpr

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

the class DrlxParseUtil method findRootNodeViaScopeRec.

private static RemoveRootNodeResult findRootNodeViaScopeRec(Expression expr, LinkedList<Expression> acc) {
    if (expr.isArrayAccessExpr()) {
        throw new RuntimeException("This doesn't work on arrayAccessExpr convert them to a method call");
    }
    if (expr instanceof EnclosedExpr) {
        return findRootNodeViaScopeRec(expr.asEnclosedExpr().getInner(), acc);
    } else if (expr instanceof CastExpr) {
        return findRootNodeViaScopeRec(expr.asCastExpr().getExpression(), acc);
    } else if (expr instanceof ThisExpr) {
        return new RemoveRootNodeResult(Optional.of(expr), expr, expr);
    } else if (expr instanceof NodeWithTraversableScope) {
        final NodeWithTraversableScope exprWithScope = (NodeWithTraversableScope) expr;
        return exprWithScope.traverseScope().flatMap((Expression scope) -> {
            if (isDslTopLevelNamespace(scope)) {
                return empty();
            }
            Expression sanitizedExpr = DrlxParseUtil.transformDrlNameExprToNameExpr(expr);
            acc.addLast(sanitizedExpr.clone());
            return of(findRootNodeViaScopeRec(scope, acc));
        }).orElse(new RemoveRootNodeResult(Optional.of(expr), expr, acc.isEmpty() ? expr : acc.getLast()));
    } else if (expr instanceof NameExpr) {
        if (!acc.isEmpty() && acc.getLast() instanceof NodeWithOptionalScope<?>) {
            ((NodeWithOptionalScope<?>) acc.getLast()).setScope(null);
            for (ListIterator<Expression> iterator = acc.listIterator(); iterator.hasNext(); ) {
                Expression e = iterator.next();
                if (e instanceof NodeWithOptionalScope) {
                    NodeWithOptionalScope<?> node = (NodeWithOptionalScope<?>) e;
                    if (iterator.hasNext()) {
                        node.setScope(acc.get(iterator.nextIndex()));
                    }
                }
            }
            return new RemoveRootNodeResult(Optional.of(expr), acc.getFirst(), acc.getLast());
        } else {
            return new RemoveRootNodeResult(Optional.of(expr), expr, expr);
        }
    }
    return new RemoveRootNodeResult(empty(), expr, expr);
}
Also used : Expression(com.github.javaparser.ast.expr.Expression) ListCreationLiteralExpression(org.drools.mvel.parser.ast.expr.ListCreationLiteralExpression) DrlxExpression(org.drools.mvel.parser.ast.expr.DrlxExpression) MapCreationLiteralExpression(org.drools.mvel.parser.ast.expr.MapCreationLiteralExpression) CastExpr(com.github.javaparser.ast.expr.CastExpr) NodeWithTraversableScope(com.github.javaparser.ast.nodeTypes.NodeWithTraversableScope) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) NodeWithOptionalScope(com.github.javaparser.ast.nodeTypes.NodeWithOptionalScope) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) ThisExpr(com.github.javaparser.ast.expr.ThisExpr)

Example 9 with ThisExpr

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

the class PackageModel method generateRulesInUnit.

private void generateRulesInUnit(String ruleUnitName, BlockStmt rulesListInitializerBody, RuleSourceResult results, ClassOrInterfaceDeclaration rulesClass) {
    results.withModel(name + "." + ruleUnitName, name + "." + rulesClass.getNameAsString());
    Collection<MethodDeclaration> ruleMethodsInUnit = ofNullable(ruleMethods.get(ruleUnitName)).map(Map::values).orElse(null);
    if (ruleMethodsInUnit == null || ruleMethodsInUnit.isEmpty()) {
        BodyDeclaration<?> getQueriesMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.Rule> getRules() {\n" + "        return java.util.Collections.emptyList();\n" + "    }\n");
        rulesClass.addMember(getQueriesMethod);
        return;
    }
    if (!ruleUnitName.equals(DEFAULT_RULE_UNIT)) {
        BodyDeclaration<?> modelNameMethod = parseBodyDeclaration("    @Override\n" + "    public String getName() {\n" + "        return super.getName() + \"." + ruleUnitName + "\";\n" + "    }\n");
        rulesClass.addMember(modelNameMethod);
        BodyDeclaration<?> modelPackageNameMethod = parseBodyDeclaration("    @Override\n" + "    public String getPackageName() {\n" + "        return super.getName();\n" + "    }\n");
        rulesClass.addMember(modelPackageNameMethod);
    }
    createAndAddGetRulesMethod(rulesClass);
    int ruleCount = ruleMethodsInUnit.size();
    boolean requiresMultipleRulesLists = ruleCount >= RULES_DECLARATION_PER_CLASS - 1;
    boolean parallelRulesLoad = ruleCount >= (RULES_DECLARATION_PER_CLASS * 3 - 1);
    MethodCallExpr parallelRulesGetter = null;
    MethodCallExpr rules = buildRulesField(rulesClass);
    if (requiresMultipleRulesLists) {
        rulesClass.addImplementedType(RulesSupplier.class);
        if (parallelRulesLoad) {
            parallelRulesGetter = new MethodCallExpr(new NameExpr(RulesSupplier.class.getCanonicalName()), "getRules");
            parallelRulesGetter.addArgument(new ThisExpr());
            rulesListInitializerBody.addStatement(new AssignExpr(new NameExpr("this.rules"), parallelRulesGetter, AssignExpr.Operator.ASSIGN));
        } else {
            MethodCallExpr add = new MethodCallExpr(new NameExpr("rules"), "addAll");
            add.addArgument("getRulesList()");
            rulesListInitializerBody.addStatement(add);
        }
    }
    ruleMethodsInUnit.parallelStream().forEach(DrlxParseUtil::transformDrlNameExprToNameExpr);
    int maxLength = ruleMethodsInUnit.parallelStream().map(MethodDeclaration::toString).mapToInt(String::length).max().orElse(1);
    int rulesPerClass = oneClassPerRule ? 1 : Math.max(50000 / maxLength, 1);
    // each method per Drlx parser result
    int count = -1;
    Map<Integer, ClassOrInterfaceDeclaration> splitted = new LinkedHashMap<>();
    for (MethodDeclaration ruleMethod : ruleMethodsInUnit) {
        String methodName = ruleMethod.getNameAsString();
        ClassOrInterfaceDeclaration rulesMethodClass = splitted.computeIfAbsent(++count / rulesPerClass, i -> {
            String className = rulesClass.getNameAsString() + (oneClassPerRule ? "_" + methodName : "RuleMethods" + i);
            return createClass(className, results);
        });
        rulesMethodClass.addMember(ruleMethod);
        if (count % RULES_DECLARATION_PER_CLASS == RULES_DECLARATION_PER_CLASS - 1) {
            int index = count / RULES_DECLARATION_PER_CLASS;
            rules = buildRulesField(results, index);
            ObjectCreationExpr newObject = new ObjectCreationExpr(null, toClassOrInterfaceType(rulesFileName + "Rules" + index), NodeList.nodeList());
            if (parallelRulesLoad) {
                parallelRulesGetter.addArgument(newObject);
            } else {
                MethodCallExpr add = new MethodCallExpr(new NameExpr("rules"), "addAll");
                add.addArgument(new MethodCallExpr(newObject, "getRulesList"));
                rulesListInitializerBody.addStatement(add);
            }
        }
        // manage in main class init block:
        rules.addArgument(new MethodCallExpr(new NameExpr(rulesMethodClass.getNameAsString()), methodName));
    }
    BodyDeclaration<?> rulesList = requiresMultipleRulesLists ? parseBodyDeclaration("java.util.List<org.drools.model.Rule> rules = new java.util.ArrayList<>(" + ruleCount + ");") : parseBodyDeclaration("java.util.List<org.drools.model.Rule> rules = getRulesList();");
    rulesClass.addMember(rulesList);
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) NameExpr(com.github.javaparser.ast.expr.NameExpr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) LinkedHashMap(java.util.LinkedHashMap) RulesSupplier(org.drools.model.RulesSupplier) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 10 with ThisExpr

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

the class CommonCodegenUtils method addMapPopulation.

/**
 * For every entry in the given map, add
 * <pre>
 *     (<i>mapName</i>).put(<i>entry_key<i/>, this::<i>entry_value_ref</i>>);
 * </pre>
 * e.g.
 * <pre>
 *     MAP_NAME.put("KEY_0", this::METHOD_015);
 *     MAP_NAME.put("KEY_3", this::METHOD_33);
 *     MAP_NAME.put("KEY_2", this::METHOD_219);
 *     MAP_NAME.put("KEY_4", this::METHOD_46);
 * </pre>
 * inside the given <code>BlockStmt</code>
 * @param toAdd
 * @param body
 * @param mapName
 */
public static void addMapPopulation(final Map<String, MethodDeclaration> toAdd, final BlockStmt body, final String mapName) {
    Map<String, Expression> toAddExpr = toAdd.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> {
        MethodReferenceExpr methodReferenceExpr = new MethodReferenceExpr();
        methodReferenceExpr.setScope(new ThisExpr());
        methodReferenceExpr.setIdentifier(entry.getValue().getNameAsString());
        return methodReferenceExpr;
    }));
    addMapPopulationExpressions(toAddExpr, body, mapName);
}
Also used : StaticJavaParser.parseClassOrInterfaceType(com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType) Arrays(java.util.Arrays) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ThisExpr(com.github.javaparser.ast.expr.ThisExpr) MISSING_VARIABLE_IN_BODY(org.kie.pmml.commons.Constants.MISSING_VARIABLE_IN_BODY) OP_TYPE(org.kie.pmml.api.enums.OP_TYPE) OpType(org.dmg.pmml.OpType) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) KiePMMLNameValue(org.kie.pmml.commons.model.tuples.KiePMMLNameValue) Type(com.github.javaparser.ast.type.Type) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) LocalTime(java.time.LocalTime) Expression(com.github.javaparser.ast.expr.Expression) MISSING_CHAINED_METHOD_DECLARATION_TEMPLATE(org.kie.pmml.commons.Constants.MISSING_CHAINED_METHOD_DECLARATION_TEMPLATE) MISSING_PARAMETER_IN_CONSTRUCTOR_INVOCATION(org.kie.pmml.commons.Constants.MISSING_PARAMETER_IN_CONSTRUCTOR_INVOCATION) Node(com.github.javaparser.ast.Node) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) DataType(org.dmg.pmml.DataType) MISSING_BODY_TEMPLATE(org.kie.pmml.commons.Constants.MISSING_BODY_TEMPLATE) Collectors(java.util.stream.Collectors) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) Objects(java.util.Objects) List(java.util.List) StaticJavaParser(com.github.javaparser.StaticJavaParser) LocalDate(java.time.LocalDate) Optional(java.util.Optional) LongLiteralExpr(com.github.javaparser.ast.expr.LongLiteralExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) TypeExpr(com.github.javaparser.ast.expr.TypeExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) Parameter(com.github.javaparser.ast.body.Parameter) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) KiePMMLInternalException(org.kie.pmml.api.exceptions.KiePMMLInternalException) MISSING_BODY_IN_METHOD(org.kie.pmml.commons.Constants.MISSING_BODY_IN_METHOD) DoubleLiteralExpr(com.github.javaparser.ast.expr.DoubleLiteralExpr) MISSING_STATIC_INITIALIZER(org.kie.pmml.commons.Constants.MISSING_STATIC_INITIALIZER) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) Statement(com.github.javaparser.ast.stmt.Statement) DATA_TYPE(org.kie.pmml.api.enums.DATA_TYPE) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) InitializerDeclaration(com.github.javaparser.ast.body.InitializerDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) MISSING_CONSTRUCTOR_IN_BODY(org.kie.pmml.commons.Constants.MISSING_CONSTRUCTOR_IN_BODY) MISSING_VARIABLE_INITIALIZER_TEMPLATE(org.kie.pmml.commons.Constants.MISSING_VARIABLE_INITIALIZER_TEMPLATE) Collections(java.util.Collections) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) IntegerLiteralExpr(com.github.javaparser.ast.expr.IntegerLiteralExpr) Expression(com.github.javaparser.ast.expr.Expression) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ThisExpr(com.github.javaparser.ast.expr.ThisExpr)

Aggregations

ThisExpr (com.github.javaparser.ast.expr.ThisExpr)14 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)9 NameExpr (com.github.javaparser.ast.expr.NameExpr)9 Expression (com.github.javaparser.ast.expr.Expression)8 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)7 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)5 AssignExpr (com.github.javaparser.ast.expr.AssignExpr)5 CastExpr (com.github.javaparser.ast.expr.CastExpr)5 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)5 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)5 SimpleName (com.github.javaparser.ast.expr.SimpleName)5 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)5 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)5 Node (com.github.javaparser.ast.Node)4 NodeList (com.github.javaparser.ast.NodeList)4 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)4 DoubleLiteralExpr (com.github.javaparser.ast.expr.DoubleLiteralExpr)4 Arrays (java.util.Arrays)4 HashMap (java.util.HashMap)4 List (java.util.List)4