Search in sources :

Example 76 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project javaparser by javaparser.

the class GenericsResolutionTest method resolveElementOfListAdvancedExample.

@Test
public void resolveElementOfListAdvancedExample() {
    CompilationUnit cu = parseSample("ElementOfList");
    ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ElementOfList");
    MethodDeclaration method = Navigator.demandMethod(clazz, "annotations");
    VariableDeclarator variableDeclarator = Navigator.demandVariableDeclaration(method, "a").get();
    Expression expression = variableDeclarator.getInitializer().get();
    ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);
    assertEquals(false, type.isTypeVariable());
    assertEquals("AnnotationExpr", type.describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Expression(com.github.javaparser.ast.expr.Expression) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Test(org.junit.Test)

Example 77 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class VariableDeclaratorTExpr method toJavaExpression.

@Override
public Node toJavaExpression() {
    Optional<Type> optInitType = initExpression.flatMap(TypedExpression::getType);
    com.github.javaparser.ast.type.Type jpType = toJPType(this.type);
    return initExpression.map(ie -> {
        Expression initializer = (Expression) ie.toJavaExpression();
        // Used to downcast map.get see testAddCastToMapGetOfDeclaration
        if (!optInitType.isPresent() || optInitType.get().equals(Object.class)) {
            initializer = new CastExpr(jpType, new EnclosedExpr(initializer));
        }
        return (Node) new VariableDeclarationExpr(new VariableDeclarator(jpType, name, initializer));
    }).orElse(new VariableDeclarationExpr(jpType, name));
}
Also used : VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Type(java.lang.reflect.Type) Optional(java.util.Optional) Expression(com.github.javaparser.ast.expr.Expression) TypeUtils.toJPType(org.drools.mvelcompiler.util.TypeUtils.toJPType) CastExpr(com.github.javaparser.ast.expr.CastExpr) Node(com.github.javaparser.ast.Node) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Type(java.lang.reflect.Type) TypeUtils.toJPType(org.drools.mvelcompiler.util.TypeUtils.toJPType) Expression(com.github.javaparser.ast.expr.Expression) CastExpr(com.github.javaparser.ast.expr.CastExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr)

Example 78 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class ForEachDowncastStmtT method toJavaExpression.

@Override
public Node toJavaExpression() {
    ForEachStmt newForEachStmt = new ForEachStmt();
    BlockStmt body = new BlockStmt();
    NodeList<VariableDeclarator> variables = nodeList();
    for (VariableDeclarator v : variableDeclarationExpr.getVariables()) {
        VariableDeclarator newVariable = v.clone();
        String newIteratorVariable = "_" + v.getNameAsString();
        VariableDeclarationExpr castAssign = new VariableDeclarationExpr(new VariableDeclarator(v.getType(), v.getName(), new CastExpr(v.getType(), new NameExpr(newIteratorVariable))));
        body.addStatement(0, castAssign);
        newVariable.setType(Object.class);
        newVariable.setName(newIteratorVariable);
        variables.add(newVariable);
    }
    body.addStatement((BlockStmt) child.toJavaExpression());
    newForEachStmt.setBody(body);
    VariableDeclarationExpr newVariables = new VariableDeclarationExpr(variables);
    newForEachStmt.setVariable(newVariables);
    return new ForEachStmt(newVariables, new NameExpr(iterable), body);
}
Also used : VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) CastExpr(com.github.javaparser.ast.expr.CastExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) ForEachStmt(com.github.javaparser.ast.stmt.ForEachStmt) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator)

Example 79 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class AccumulateInline method parseInitBlock.

private void parseInitBlock() {
    MethodDeclaration initMethod = getMethodFromTemplateClass("init");
    String mvelBlock = addCurlyBracesToBlock(addSemicolon(accumulateDescr.getInitCode()));
    CompiledBlockResult initCodeCompilationResult = mvelCompiler.compileStatement(mvelBlock);
    BlockStmt initBlock = initCodeCompilationResult.statementResults();
    for (Statement stmt : initBlock.getStatements()) {
        final BlockStmt initMethodBody = initMethod.getBody().orElseThrow(InvalidInlineTemplateException::new);
        if (stmt.isExpressionStmt() && stmt.asExpressionStmt().getExpression().isVariableDeclarationExpr()) {
            VariableDeclarationExpr vdExpr = stmt.asExpressionStmt().getExpression().asVariableDeclarationExpr();
            for (VariableDeclarator vd : vdExpr.getVariables()) {
                final String variableName = vd.getNameAsString();
                contextFieldNames.add(variableName);
                contextData.addField(vd.getType(), variableName, Modifier.publicModifier().getKeyword());
                Optional<Expression> optInitializer = vd.getInitializer();
                optInitializer.ifPresent(initializer -> {
                    Expression target = new FieldAccessExpr(getDataNameExpr(), variableName);
                    Statement initStmt = new ExpressionStmt(new AssignExpr(target, initializer, AssignExpr.Operator.ASSIGN));
                    initMethodBody.addStatement(initStmt);
                    initStmt.findAll(NameExpr.class).stream().map(Node::toString).filter(context::hasDeclaration).forEach(usedExternalDeclarations::add);
                });
                accumulateDeclarations.add(new DeclarationSpec(variableName, DrlxParseUtil.getClassFromContext(context.getTypeResolver(), vd.getType().asString())));
            }
        }
    }
}
Also used : VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) StaticJavaParser.parseStatement(com.github.javaparser.StaticJavaParser.parseStatement) Statement(com.github.javaparser.ast.stmt.Statement) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) Node(com.github.javaparser.ast.Node) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) Expression(com.github.javaparser.ast.expr.Expression) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) CompiledBlockResult(org.drools.mvelcompiler.CompiledBlockResult)

Example 80 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator 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<AssignExpr> assignExprs = rhs.findAll(AssignExpr.class);
    List<MethodCallExpr> updateExprs = new ArrayList<>();
    Map<String, Type> rhsBodyDeclarations = new HashMap<>();
    for (VariableDeclarator variableDeclarator : rhs.findAll(VariableDeclarator.class)) {
        rhsBodyDeclarations.put(variableDeclarator.getNameAsString(), variableDeclarator.getType());
    }
    for (MethodCallExpr methodCallExpr : methodCallExprs) {
        if (!methodCallExpr.getScope().isPresent() && isImplicitDroolsMethod(methodCallExpr)) {
            if (methodCallExpr.getNameAsString().equals("insertLogical") && !TruthMaintenanceSystemFactory.present()) {
                context.addCompilationError(new MissingDependencyError(TruthMaintenanceSystemFactory.NO_TMS));
            }
            methodCallExpr.setScope(new NameExpr("drools"));
        }
        if (hasDroolsScope(methodCallExpr) || hasDroolsAsParameter(methodCallExpr)) {
            if (knowledgeHelperMethods.contains(methodCallExpr.getNameAsString())) {
                methodCallExpr.setScope(createAsKnowledgeHelperExpression());
            } else if (methodCallExpr.getNameAsString().equals("update")) {
                if (methodCallExpr.toString().contains("FactHandle")) {
                    methodCallExpr.setScope(new NameExpr("((org.drools.modelcompiler.consequence.DroolsImpl) drools)"));
                }
                updateExprs.add(methodCallExpr);
            } else if (methodCallExpr.getNameAsString().equals("retract")) {
                methodCallExpr.setName(new SimpleName("delete"));
            }
            requireDrools.set(true);
        }
    }
    Set<String> initializedBitmaskFields = new HashSet<>();
    for (MethodCallExpr updateExpr : updateExprs) {
        Expression argExpr = updateExpr.getArgument(0);
        if (argExpr instanceof NameExpr) {
            String updatedVar = ((NameExpr) argExpr).getNameAsString();
            Class<?> updatedClass = classFromRHSDeclarations(rhsBodyDeclarations, updatedVar);
            // We might need to generate the domain metadata class for types used in consequence
            // without an explicit pattern. See CompilerTest.testConsequenceInsertThenUpdate
            context.getPackageModel().registerDomainClass(updatedClass);
            if (context.isPropertyReactive(updatedClass)) {
                if (!initializedBitmaskFields.contains(updatedVar)) {
                    Set<String> modifiedProps = findModifiedProperties(methodCallExprs, updateExpr, updatedVar, updatedClass);
                    modifiedProps.addAll(findModifiedPropertiesFromAssignment(assignExprs, updateExpr, updatedVar, updatedClass));
                    MethodCallExpr bitMaskCreation = createBitMaskInitialization(updatedClass, modifiedProps);
                    AssignExpr bitMaskAssign = createBitMaskField(updatedVar, bitMaskCreation);
                    if (!DrlxParseUtil.hasDuplicateExpr(ruleBlock, bitMaskAssign)) {
                        ruleBlock.addStatement(bitMaskAssign);
                    }
                }
                updateExpr.addArgument("mask_" + updatedVar);
                initializedBitmaskFields.add(updatedVar);
            }
        }
    }
    return requireDrools.get();
}
Also used : HashMap(java.util.HashMap) SimpleName(com.github.javaparser.ast.expr.SimpleName) ArrayList(java.util.ArrayList) NameExpr(com.github.javaparser.ast.expr.NameExpr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Type(com.github.javaparser.ast.type.Type) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) MissingDependencyError(org.drools.compiler.compiler.MissingDependencyError) Expression(com.github.javaparser.ast.expr.Expression) StaticJavaParser.parseExpression(com.github.javaparser.StaticJavaParser.parseExpression) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) HashSet(java.util.HashSet)

Aggregations

VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)110 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)50 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)44 Expression (com.github.javaparser.ast.expr.Expression)43 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)41 CommonCodegenUtils.getVariableDeclarator (org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator)39 NameExpr (com.github.javaparser.ast.expr.NameExpr)33 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)32 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)30 Test (org.junit.Test)25 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)24 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)18 VariableDeclarationExpr (com.github.javaparser.ast.expr.VariableDeclarationExpr)17 CompilationUnit (com.github.javaparser.ast.CompilationUnit)16 NodeList (com.github.javaparser.ast.NodeList)16 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)14 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)13 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)13 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)11 Parameter (com.github.javaparser.ast.body.Parameter)9