Search in sources :

Example 26 with SimpleName

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

the class KiePMMLDroolsModelFactoryUtilsTest method setConstructor.

@Test
public void setConstructor() {
    Model model = new TreeModel();
    PMML_MODEL pmmlModel = PMML_MODEL.byName(model.getClass().getSimpleName());
    ConstructorDeclaration constructorDeclaration = MODEL_TEMPLATE.getDefaultConstructor().get();
    SimpleName tableName = new SimpleName("TABLE_NAME");
    String targetField = "TARGET_FIELD";
    MINING_FUNCTION miningFunction = MINING_FUNCTION.CLASSIFICATION;
    String kModulePackageName = getSanitizedPackageName("kModulePackageName");
    KiePMMLDroolsModelFactoryUtils.setConstructor(model, constructorDeclaration, tableName, targetField, miningFunction, kModulePackageName);
    Map<Integer, Expression> superInvocationExpressionsMap = new HashMap<>();
    Map<String, Expression> assignExpressionMap = new HashMap<>();
    assignExpressionMap.put("targetField", new StringLiteralExpr(targetField));
    assignExpressionMap.put("miningFunction", new NameExpr(miningFunction.getClass().getName() + "." + miningFunction.name()));
    assignExpressionMap.put("pmmlMODEL", new NameExpr(pmmlModel.getClass().getName() + "." + pmmlModel.name()));
    assignExpressionMap.put("kModulePackageName", new StringLiteralExpr(kModulePackageName));
    assertTrue(commonEvaluateConstructor(constructorDeclaration, tableName.asString(), superInvocationExpressionsMap, assignExpressionMap));
}
Also used : HashMap(java.util.HashMap) SimpleName(com.github.javaparser.ast.expr.SimpleName) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) TreeModel(org.dmg.pmml.tree.TreeModel) Expression(com.github.javaparser.ast.expr.Expression) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Model(org.dmg.pmml.Model) TreeModel(org.dmg.pmml.tree.TreeModel) PMML_MODEL(org.kie.pmml.api.enums.PMML_MODEL) MINING_FUNCTION(org.kie.pmml.api.enums.MINING_FUNCTION) Test(org.junit.Test)

Example 27 with SimpleName

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

the class ExpressionTyper method thisExpr.

private TypedExpressionCursor thisExpr(Expression drlxExpr, List<Node> childNodes, boolean isInLineCast, java.lang.reflect.Type originalTypeCursor) {
    TypedExpressionCursor teCursor;
    if (childNodes.size() > 1 && !isInLineCast) {
        SimpleName fieldName = null;
        if (childNodes.get(1) instanceof NameExpr) {
            fieldName = ((NameExpr) childNodes.get(1)).getName();
        } else if (childNodes.get(1) instanceof SimpleName) {
            fieldName = (SimpleName) childNodes.get(1);
        }
        if (fieldName != null) {
            context.addReactOnProperties(getFieldName(drlxExpr, fieldName));
        }
    }
    teCursor = new TypedExpressionCursor(new NameExpr(THIS_PLACEHOLDER), originalTypeCursor);
    return teCursor;
}
Also used : SimpleName(com.github.javaparser.ast.expr.SimpleName) DrlxParseUtil.transformDrlNameExprToNameExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.transformDrlNameExprToNameExpr) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr)

Example 28 with SimpleName

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

the class ExpressionTyper method toTypedExpressionFromMethodCallOrField.

private TypedExpressionResult toTypedExpressionFromMethodCallOrField(Expression drlxExpr) {
    if (drlxExpr instanceof FieldAccessExpr) {
        // try to see if it's a constant
        final Optional<TypedExpression> typedExpression = tryParseAsConstantField(ruleContext.getTypeResolver(), ((FieldAccessExpr) drlxExpr).getScope(), ((FieldAccessExpr) drlxExpr).getNameAsString());
        if (typedExpression.isPresent()) {
            return new TypedExpressionResult(typedExpression, context);
        }
    }
    if (patternType == null && drlxExpr instanceof NullSafeFieldAccessExpr) {
        // try to see if it's a constant
        final Optional<TypedExpression> typedExpression = tryParseAsConstantField(ruleContext.getTypeResolver(), ((NullSafeFieldAccessExpr) drlxExpr).getScope(), ((NullSafeFieldAccessExpr) drlxExpr).getNameAsString());
        if (typedExpression.isPresent()) {
            return new TypedExpressionResult(typedExpression, context);
        }
    }
    final List<Node> childrenNodes = flattenScope(ruleContext.getTypeResolver(), drlxExpr);
    final Node firstChild = childrenNodes.get(0);
    boolean isInLineCast = firstChild instanceof InlineCastExpr;
    java.lang.reflect.Type originalTypeCursor;
    final Node firstNode;
    if (isInLineCast) {
        InlineCastExpr inlineCast = (InlineCastExpr) firstChild;
        originalTypeCursor = originalTypeCursorFromInlineCast(inlineCast);
        firstNode = inlineCast.getExpression();
        if (inlineCast.getExpression().isThisExpr()) {
            context.setInlineCastExpression(Optional.of(new InstanceOfExpr(new NameExpr(THIS_PLACEHOLDER), (ReferenceType) inlineCast.getType())));
        } else {
            context.setInlineCastExpression(toTypedExpression(inlineCast.getExpression()).getTypedExpression().map(TypedExpression::getExpression).map(expr -> new InstanceOfExpr(expr, (ReferenceType) inlineCast.getType())));
        }
    } else {
        originalTypeCursor = patternType;
        firstNode = firstChild;
    }
    if (originalTypeCursor != null && originalTypeCursor.equals(Object.class)) {
        // try infer type  from the declarations
        final Optional<DeclarationSpec> declarationById = ruleContext.getDeclarationById(printNode(firstChild));
        originalTypeCursor = declarationById.map(d -> (java.lang.reflect.Type) d.getDeclarationClass()).orElse(originalTypeCursor);
    }
    final Optional<TypedExpressionCursor> teCursor = processFirstNode(drlxExpr, childrenNodes, firstNode, isInLineCast, originalTypeCursor);
    if (firstNode instanceof MethodCallExpr) {
        MethodCallExpr me = (MethodCallExpr) firstNode;
        addReactOnProperty(me.getNameAsString(), me.getArguments());
    }
    if (firstNode instanceof NullSafeMethodCallExpr) {
        NullSafeMethodCallExpr me = (NullSafeMethodCallExpr) firstNode;
        addReactOnProperty(me.getNameAsString(), me.getArguments());
    }
    if (!teCursor.isPresent()) {
        return new TypedExpressionResult(empty(), context);
    }
    Expression previous = teCursor.get().expressionCursor;
    java.lang.reflect.Type typeCursor = teCursor.get().typeCursor;
    List<Node> childrenWithoutFirst = childrenNodes.subList(1, childrenNodes.size());
    for (Node part : childrenWithoutFirst) {
        if (part instanceof SimpleName) {
            String field = part.toString();
            TypedExpression expression = nameExprToMethodCallExpr(field, typeCursor, previous, ruleContext);
            if (expression == null) {
                ruleContext.addCompilationError(new InvalidExpressionErrorResult("Unknown field " + field + " on " + typeCursor));
                break;
            }
            typeCursor = expression.getType();
            previous = expression.getExpression();
        } else if (part instanceof MethodCallExpr) {
            TypedExpressionCursor typedExpr = methodCallExpr((MethodCallExpr) part, typeCursor, previous);
            typeCursor = typedExpr.typeCursor;
            previous = typedExpr.expressionCursor;
        } else if (part instanceof NullSafeMethodCallExpr) {
            TypedExpressionCursor typedExpr = nullSafeMethodCallExpr((NullSafeMethodCallExpr) part, typeCursor, previous);
            typeCursor = typedExpr.typeCursor;
            previous = typedExpr.expressionCursor;
        } else if (part instanceof InlineCastExpr && ((InlineCastExpr) part).getExpression() instanceof FieldAccessExpr) {
            InlineCastExpr inlineCastExprPart = (InlineCastExpr) part;
            final FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) inlineCastExprPart.getExpression();
            final TypedExpression toMethodCallExpr = nameExprToMethodCallExpr(fieldAccessExpr.getNameAsString(), typeCursor, previous, ruleContext);
            if (toMethodCallExpr == null) {
                ruleContext.addCompilationError(new InvalidExpressionErrorResult("Unknown field " + fieldAccessExpr.getNameAsString() + " on " + typeCursor));
                break;
            }
            final Class<?> castClass = getClassFromType(ruleContext.getTypeResolver(), inlineCastExprPart.getType());
            previous = addCastToExpression(castClass, toMethodCallExpr.getExpression(), false);
            typeCursor = castClass;
        } else if (part instanceof ArrayAccessExpr) {
            final ArrayAccessExpr inlineCastExprPart = (ArrayAccessExpr) part;
            TypedExpressionCursor typedExpr = arrayAccessExpr(inlineCastExprPart, typeCursor, previous).orElseThrow(() -> new NoSuchElementException("ArrayAccessExpr doesn't contain TypedExpressionCursor!"));
            typeCursor = typedExpr.typeCursor;
            previous = typedExpr.expressionCursor;
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return new TypedExpressionResult(of(new TypedExpression(previous, typeCursor, accessorToFieldName(drlxExpr))), context);
}
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) PrintUtil.printNode(org.drools.mvel.parser.printer.PrintUtil.printNode) Node(com.github.javaparser.ast.Node) SimpleName(com.github.javaparser.ast.expr.SimpleName) DrlxParseUtil.transformDrlNameExprToNameExpr(org.drools.modelcompiler.builder.generator.DrlxParseUtil.transformDrlNameExprToNameExpr) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) NullSafeFieldAccessExpr(org.drools.mvel.parser.ast.expr.NullSafeFieldAccessExpr) UnificationTypedExpression(org.drools.modelcompiler.builder.generator.UnificationTypedExpression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) ArrayAccessExpr(com.github.javaparser.ast.expr.ArrayAccessExpr) FlattenScope.transformFullyQualifiedInlineCastExpr(org.drools.modelcompiler.builder.generator.expressiontyper.FlattenScope.transformFullyQualifiedInlineCastExpr) InlineCastExpr(org.drools.mvel.parser.ast.expr.InlineCastExpr) FullyQualifiedInlineCastExpr(org.drools.mvel.parser.ast.expr.FullyQualifiedInlineCastExpr) InstanceOfExpr(com.github.javaparser.ast.expr.InstanceOfExpr) NullSafeFieldAccessExpr(org.drools.mvel.parser.ast.expr.NullSafeFieldAccessExpr) 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) NullSafeMethodCallExpr(org.drools.mvel.parser.ast.expr.NullSafeMethodCallExpr) NoSuchElementException(java.util.NoSuchElementException) 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 29 with SimpleName

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

the class AbstractExpressionBuilder method containsThis.

protected boolean containsThis(TypedExpression typedExpression) {
    Expression expr = typedExpression.getExpression();
    Optional<String> opt = expr.findAll(NameExpr.class).stream().map(NameExpr::getName).map(SimpleName::getIdentifier).findFirst();
    return opt.map(s -> s.equals(THIS_PLACEHOLDER)).orElse(false);
}
Also used : ClassExpr(com.github.javaparser.ast.expr.ClassExpr) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) ClassUtil.isAccessibleProperties(org.drools.modelcompiler.util.ClassUtil.isAccessibleProperties) BigDecimal(java.math.BigDecimal) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) BigDecimalLiteralExpr(org.drools.mvel.parser.ast.expr.BigDecimalLiteralExpr) LiteralExpr(com.github.javaparser.ast.expr.LiteralExpr) DrlxParseUtil.generateLambdaWithoutParameters(org.drools.modelcompiler.builder.generator.DrlxParseUtil.generateLambdaWithoutParameters) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) BigInteger(java.math.BigInteger) Expression(com.github.javaparser.ast.expr.Expression) ClassUtil.toRawClass(org.drools.modelcompiler.util.ClassUtil.toRawClass) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) CoercedExpression(org.drools.modelcompiler.builder.generator.drlxparse.CoercedExpression) THIS_PLACEHOLDER(org.drools.modelcompiler.builder.generator.DrlxParseUtil.THIS_PLACEHOLDER) Index(org.drools.model.Index) MultipleDrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.MultipleDrlxParseSuccess) Collectors(java.util.stream.Collectors) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) Resource(org.kie.api.io.Resource) List(java.util.List) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) SingleDrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.SingleDrlxParseSuccess) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) BoxedParameters(org.drools.modelcompiler.builder.generator.BoxedParameters) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) DrlxParseUtil.toStringLiteral(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toStringLiteral) DrlxParseUtil.toJavaParserType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toJavaParserType) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) RuleDescr(org.drools.drl.ast.descr.RuleDescr) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) DrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseSuccess) PrintUtil.printNode(org.drools.mvel.parser.printer.PrintUtil.printNode) Parameter(com.github.javaparser.ast.body.Parameter) CastExpr(com.github.javaparser.ast.expr.CastExpr) NodeWithOptionalScope(com.github.javaparser.ast.nodeTypes.NodeWithOptionalScope) BigIntegerLiteralExpr(org.drools.mvel.parser.ast.expr.BigIntegerLiteralExpr) DoubleLiteralExpr(com.github.javaparser.ast.expr.DoubleLiteralExpr) Optional.ofNullable(java.util.Optional.ofNullable) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) NameExpr(com.github.javaparser.ast.expr.NameExpr) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) PrimitiveType(com.github.javaparser.ast.type.PrimitiveType) DrlxParseUtil.isThisExpression(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isThisExpression) Expression(com.github.javaparser.ast.expr.Expression) CoercedExpression(org.drools.modelcompiler.builder.generator.drlxparse.CoercedExpression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) NameExpr(com.github.javaparser.ast.expr.NameExpr)

Example 30 with SimpleName

use of com.github.javaparser.ast.expr.SimpleName 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

SimpleName (com.github.javaparser.ast.expr.SimpleName)34 Test (org.junit.Test)17 Expression (com.github.javaparser.ast.expr.Expression)15 NameExpr (com.github.javaparser.ast.expr.NameExpr)11 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)9 BinaryExpr (com.github.javaparser.ast.expr.BinaryExpr)9 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)9 ArrayList (java.util.ArrayList)8 List (java.util.List)8 HalfBinaryExpr (org.drools.mvel.parser.ast.expr.HalfBinaryExpr)8 Parameter (com.github.javaparser.ast.body.Parameter)7 NodeList (com.github.javaparser.ast.NodeList)6 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)6 Node (com.github.javaparser.ast.Node)5 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)5 EnclosedExpr (com.github.javaparser.ast.expr.EnclosedExpr)5 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)5 HashMap (java.util.HashMap)5 DrlxExpression (org.drools.mvel.parser.ast.expr.DrlxExpression)5 CompilationUnit (com.github.javaparser.ast.CompilationUnit)4