Search in sources :

Example 76 with Expression

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

the class ConstraintPrintVisitor method printArguments.

public void printArguments(final NodeList<Expression> args, final Void arg) {
    printer.print("(");
    if (!isNullOrEmpty(args)) {
        boolean columnAlignParameters = (args.size() > 1) && configuration.get(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.COLUMN_ALIGN_PARAMETERS)).map(ConfigurationOption::asBoolean).orElse(false);
        if (columnAlignParameters) {
            printer.indentWithAlignTo(printer.getCursor().column);
        }
        for (final Iterator<Expression> i = args.iterator(); i.hasNext(); ) {
            final Expression e = i.next();
            e.accept(this, arg);
            if (i.hasNext()) {
                printer.print(",");
                if (columnAlignParameters) {
                    printer.println();
                } else {
                    printer.print(" ");
                }
            }
        }
        if (columnAlignParameters) {
            printer.unindent();
        }
    }
    printer.print(")");
}
Also used : DefaultConfigurationOption(com.github.javaparser.printer.configuration.DefaultConfigurationOption) 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) ConfigurationOption(com.github.javaparser.printer.configuration.ConfigurationOption) DefaultConfigurationOption(com.github.javaparser.printer.configuration.DefaultConfigurationOption)

Example 77 with Expression

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

the class MethodCallExprT method coercedMapArguments.

private List<Expression> coercedMapArguments() {
    Expression key = (Expression) arguments.get(0).toJavaExpression();
    Expression originalValue = (Expression) arguments.get(1).toJavaExpression();
    Optional<Type> scopeType = scope.flatMap(TypedExpression::getType);
    Expression coercedValue = coerceMapValueToString(scopeType, originalValue);
    return Arrays.asList(key, coercedValue);
}
Also used : Type(java.lang.reflect.Type) Expression(com.github.javaparser.ast.expr.Expression)

Example 78 with Expression

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

the class PackageModel method getRulesSource.

public RuleSourceResult getRulesSource() {
    boolean hasRuleUnit = !ruleUnits.isEmpty();
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(name);
    manageImportForCompilationUnit(cu);
    ClassOrInterfaceDeclaration rulesClass = cu.addClass(rulesFileName);
    rulesClass.addImplementedType(Model.class.getCanonicalName());
    if (hasRuleUnit) {
        rulesClass.addModifier(Modifier.Keyword.ABSTRACT);
    }
    BodyDeclaration<?> dateFormatter = parseBodyDeclaration("public final static java.time.format.DateTimeFormatter " + DATE_TIME_FORMATTER_FIELD + " = new java.time.format.DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(org.drools.core.util.DateUtils.getDateFormatMask()).toFormatter(java.util.Locale.ENGLISH);\n");
    rulesClass.addMember(dateFormatter);
    BodyDeclaration<?> getNameMethod = parseBodyDeclaration("    @Override\n" + "    public String getName() {\n" + "        return \"" + name + "\";\n" + "    }\n");
    rulesClass.addMember(getNameMethod);
    String entryPointsBuilder = entryPoints.isEmpty() ? "java.util.Collections.emptyList()" : "java.util.Arrays.asList(D.entryPoint(\"" + entryPoints.stream().collect(joining("\"), D.entryPoint(\"")) + "\"))";
    BodyDeclaration<?> getEntryPointsMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.EntryPoint> getEntryPoints() {\n" + "        return " + entryPointsBuilder + ";\n" + "    }\n");
    rulesClass.addMember(getEntryPointsMethod);
    BodyDeclaration<?> getGlobalsMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.Global> getGlobals() {\n" + "        return globals;\n" + "    }\n");
    rulesClass.addMember(getGlobalsMethod);
    BodyDeclaration<?> getTypeMetaDataMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.TypeMetaData> getTypeMetaDatas() {\n" + "        return typeMetaDatas;\n" + "    }\n");
    rulesClass.addMember(getTypeMetaDataMethod);
    for (Map.Entry<String, TypedExpression> dateField : dateFields.entrySet()) {
        FieldDeclaration f = rulesClass.addField(dateField.getValue().getJPType(), dateField.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        f.getVariables().get(0).setInitializer(dateField.getValue().getExpression());
    }
    for (Map.Entry<String, MethodCallExpr> windowReference : windowReferences.entrySet()) {
        FieldDeclaration f = rulesClass.addField(WINDOW_REFERENCE_TYPE, windowReference.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        f.getVariables().get(0).setInitializer(windowReference.getValue());
    }
    for (Map.Entry<String, Class<?>> g : getGlobals().entrySet()) {
        addGlobalField(rulesClass, getName(), g.getKey(), g.getValue());
    }
    for (Map.Entry<String, QueryGenerator.QueryDefWithType> queryDef : queryDefWithType.entrySet()) {
        FieldDeclaration field = rulesClass.addField(queryDef.getValue().getQueryType(), queryDef.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        field.getVariables().get(0).setInitializer(queryDef.getValue().getMethodCallExpr());
    }
    // instance initializer block.
    // add to `rules` list the result of invoking each method for rule
    InitializerDeclaration rulesListInitializer = new InitializerDeclaration();
    BlockStmt rulesListInitializerBody = new BlockStmt();
    rulesListInitializer.setBody(rulesListInitializerBody);
    buildArtifactsDeclaration(getGlobals().keySet(), rulesClass, rulesListInitializerBody, "org.drools.model.Global", "globals", true);
    if (!typeMetaDataExpressions.isEmpty()) {
        BodyDeclaration<?> typeMetaDatasList = parseBodyDeclaration("java.util.List<org.drools.model.TypeMetaData> typeMetaDatas = new java.util.ArrayList<>();");
        rulesClass.addMember(typeMetaDatasList);
        for (Expression expr : typeMetaDataExpressions) {
            addInitStatement(rulesListInitializerBody, expr, "typeMetaDatas");
        }
    } else {
        BodyDeclaration<?> typeMetaDatasList = parseBodyDeclaration("java.util.List<org.drools.model.TypeMetaData> typeMetaDatas = java.util.Collections.emptyList();");
        rulesClass.addMember(typeMetaDatasList);
    }
    functions.forEach(rulesClass::addMember);
    RuleSourceResult results = new RuleSourceResult(cu);
    if (hasRuleUnit) {
        ruleMethods.keySet().forEach(unitName -> {
            String className = rulesFileName + "_" + unitName;
            ClassOrInterfaceDeclaration unitClass = createClass(className, results);
            unitClass.addExtendedType(rulesFileName);
            InitializerDeclaration unitInitializer = new InitializerDeclaration();
            BlockStmt unitInitializerBody = new BlockStmt();
            unitInitializer.setBody(unitInitializerBody);
            generateRulesInUnit(unitName, unitInitializerBody, results, unitClass);
            Set<QueryModel> queries = queriesByRuleUnit.get(unitName);
            Collection<String> queryNames = queries == null ? Collections.emptyList() : queries.stream().map(QueryModel::getName).map(name -> QUERY_METHOD_PREFIX + name).collect(toList());
            Collection<MethodDeclaration> queryImpls = queryNames.stream().map(queryMethods::get).collect(toList());
            generateQueriesInUnit(unitClass, unitInitializerBody, queryNames, queryImpls);
            if (!unitInitializerBody.getStatements().isEmpty()) {
                unitClass.addMember(unitInitializer);
            }
        });
    } else {
        generateRulesInUnit(DEFAULT_RULE_UNIT, rulesListInitializerBody, results, rulesClass);
        generateQueriesInUnit(rulesClass, rulesListInitializerBody, queryMethods.keySet(), queryMethods.values());
    }
    if (!rulesListInitializerBody.getStatements().isEmpty()) {
        rulesClass.addMember(rulesListInitializer);
    }
    return results;
}
Also used : ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) InitializerDeclaration(com.github.javaparser.ast.body.InitializerDeclaration) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) Model(org.drools.model.Model) CreatedClass(org.drools.modelcompiler.util.lambdareplace.CreatedClass) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 79 with Expression

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

the class ExecModelLambdaPostProcessor method convertFromCall.

private void convertFromCall(MethodCallExpr methodCallExpr) {
    Optional<LambdaExpr> lambdaOpt = methodCallExpr.getArguments().stream().filter(Expression::isLambdaExpr).map(Expression::asLambdaExpr).findFirst();
    if (!lambdaOpt.isPresent()) {
        // Don't need to handle. e.g. D.from(var_$children)
        return;
    }
    LambdaExpr lambdaExpr = lambdaOpt.get();
    Optional<MaterializedLambdaExtractor> extractorOpt = createMaterializedLambdaExtractor(lambdaExpr);
    if (!extractorOpt.isPresent()) {
        logger.debug("Unable to create MaterializedLambdaExtractor for {}", lambdaExpr);
        return;
    }
    MaterializedLambdaExtractor extractor = extractorOpt.get();
    extractLambdaFromMethodCall(methodCallExpr, (i) -> extractor);
}
Also used : Expression(com.github.javaparser.ast.expr.Expression) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr)

Example 80 with Expression

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

the class ExecModelLambdaPostProcessor method toMaterializedLambdaFactory.

private MaterializedLambda.BitMaskVariable toMaterializedLambdaFactory(AssignExpr ae) {
    String maskName = ae.getTarget().asVariableDeclarationExpr().getVariables().iterator().next().getNameAsString();
    MethodCallExpr maskInit = ae.getValue().asMethodCallExpr();
    if (maskInit.getArguments().isEmpty()) {
        return new MaterializedLambda.AllSetButLastBitMask(maskName);
    } else {
        NodeList<Expression> arguments = maskInit.getArguments();
        String domainClassMetadata = PrintUtil.printNode(arguments.get(0));
        List<String> fields = arguments.subList(1, arguments.size()).stream().map(PrintUtil::printNode).collect(Collectors.toList());
        return new MaterializedLambda.BitMaskVariableWithFields(domainClassMetadata, fields, maskName);
    }
}
Also used : Expression(com.github.javaparser.ast.expr.Expression) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

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