Search in sources :

Example 76 with NodeList

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

the class KiePMMLDiscretizeFactory method getDiscretizeVariableDeclaration.

static BlockStmt getDiscretizeVariableDeclaration(final String variableName, final Discretize discretize) {
    final MethodDeclaration methodDeclaration = DISCRETIZE_TEMPLATE.getMethodsByName(GETKIEPMMLDISCRETIZE).get(0).clone();
    final BlockStmt discretizeBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration)));
    final VariableDeclarator variableDeclarator = getVariableDeclarator(discretizeBody, DISCRETIZE).orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, DISCRETIZE, discretizeBody)));
    variableDeclarator.setName(variableName);
    final BlockStmt toReturn = new BlockStmt();
    int counter = 0;
    final NodeList<Expression> arguments = new NodeList<>();
    for (DiscretizeBin discretizeBin : discretize.getDiscretizeBins()) {
        String nestedVariableName = String.format(VARIABLE_NAME_TEMPLATE, variableName, counter);
        arguments.add(new NameExpr(nestedVariableName));
        BlockStmt toAdd = getDiscretizeBinVariableDeclaration(nestedVariableName, discretizeBin);
        toAdd.getStatements().forEach(toReturn::addStatement);
        counter++;
    }
    final ObjectCreationExpr objectCreationExpr = variableDeclarator.getInitializer().orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, DISCRETIZE, toReturn))).asObjectCreationExpr();
    final Expression nameExpr = new StringLiteralExpr(discretize.getField().getValue());
    final Expression mapMissingToExpr = getExpressionForObject(discretize.getMapMissingTo());
    final Expression defaultValueExpr = getExpressionForObject(discretize.getDefaultValue());
    final Expression dataTypeExpression = getExpressionForDataType(discretize.getDataType());
    objectCreationExpr.getArguments().set(0, nameExpr);
    objectCreationExpr.getArguments().get(2).asMethodCallExpr().setArguments(arguments);
    objectCreationExpr.getArguments().set(3, mapMissingToExpr);
    objectCreationExpr.getArguments().set(4, defaultValueExpr);
    objectCreationExpr.getArguments().set(5, dataTypeExpression);
    discretizeBody.getStatements().forEach(toReturn::addStatement);
    return toReturn;
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NodeList(com.github.javaparser.ast.NodeList) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) CommonCodegenUtils.getVariableDeclarator(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Expression(com.github.javaparser.ast.expr.Expression) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) DiscretizeBin(org.dmg.pmml.DiscretizeBin)

Example 77 with NodeList

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

the class KiePMMLRegressionTableFactory method getNumericPredictorExpression.

/**
 * Create a <b>NumericPredictor</b> <code>CastExpr</code>
 * @param numericPredictor
 * @return
 */
static CastExpr getNumericPredictorExpression(final NumericPredictor numericPredictor) {
    boolean withExponent = !Objects.equals(1, numericPredictor.getExponent());
    final String lambdaExpressionMethodName = withExponent ? "evaluateNumericWithExponent" : "evaluateNumericWithoutExponent";
    final String parameterName = "input";
    final MethodCallExpr lambdaMethodCallExpr = new MethodCallExpr();
    lambdaMethodCallExpr.setName(lambdaExpressionMethodName);
    lambdaMethodCallExpr.setScope(new NameExpr(KiePMMLRegressionTable.class.getSimpleName()));
    final NodeList<Expression> arguments = new NodeList<>();
    arguments.add(0, new NameExpr(parameterName));
    arguments.add(1, getExpressionForObject(numericPredictor.getCoefficient().doubleValue()));
    if (withExponent) {
        arguments.add(2, getExpressionForObject(numericPredictor.getExponent().doubleValue()));
    }
    lambdaMethodCallExpr.setArguments(arguments);
    final ExpressionStmt lambdaExpressionStmt = new ExpressionStmt(lambdaMethodCallExpr);
    final LambdaExpr lambdaExpr = new LambdaExpr();
    final Parameter lambdaParameter = new Parameter(new UnknownType(), parameterName);
    lambdaExpr.setParameters(NodeList.nodeList(lambdaParameter));
    lambdaExpr.setBody(lambdaExpressionStmt);
    final String doubleClassName = Double.class.getSimpleName();
    final ClassOrInterfaceType serializableFunctionType = getTypedClassOrInterfaceTypeByTypeNames(SerializableFunction.class.getCanonicalName(), Arrays.asList(doubleClassName, doubleClassName));
    final CastExpr toReturn = new CastExpr();
    toReturn.setType(serializableFunctionType);
    toReturn.setExpression(lambdaExpr);
    return toReturn;
}
Also used : SerializableFunction(org.kie.pmml.api.iinterfaces.SerializableFunction) NodeList(com.github.javaparser.ast.NodeList) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) UnknownType(com.github.javaparser.ast.type.UnknownType) Expression(com.github.javaparser.ast.expr.Expression) CastExpr(com.github.javaparser.ast.expr.CastExpr) Parameter(com.github.javaparser.ast.body.Parameter) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 78 with NodeList

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

the class KiePMMLCharacteristicsFactory method setCharacteristicsVariableDeclaration.

static void setCharacteristicsVariableDeclaration(final String characteristicsClassName, final Characteristics characteristics, final List<Field<?>> fields, final ClassOrInterfaceDeclaration characteristicsTemplate) {
    int counter = 0;
    NodeList<Expression> arguments = new NodeList<>();
    for (Characteristic characteristic : characteristics.getCharacteristics()) {
        String characteristicVariableName = String.format(VARIABLE_NAME_TEMPLATE, characteristicsClassName, counter);
        addGetCharacteristicMethod(characteristicVariableName, characteristic, fields, characteristicsTemplate);
        MethodCallExpr toAdd = new MethodCallExpr();
        toAdd.setScope(new NameExpr(characteristicsClassName));
        toAdd.setName("get" + characteristicVariableName);
        arguments.add(toAdd);
        counter++;
    }
    final ConstructorDeclaration constructorDeclaration = characteristicsTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format(MISSING_DEFAULT_CONSTRUCTOR, characteristicsTemplate.getName())));
    constructorDeclaration.setName(characteristicsClassName);
    final BlockStmt body = constructorDeclaration.getBody();
    final ExplicitConstructorInvocationStmt superStatement = CommonCodegenUtils.getExplicitConstructorInvocationStmt(body).orElseThrow(() -> new KiePMMLException(String.format(MISSING_CONSTRUCTOR_IN_BODY, body)));
    superStatement.setArgument(0, new StringLiteralExpr(characteristicsClassName));
    superStatement.setArgument(2, getArraysAsListInvocationMethodCall(arguments));
}
Also used : NodeList(com.github.javaparser.ast.NodeList) Characteristic(org.dmg.pmml.scorecard.Characteristic) KiePMMLCharacteristic(org.kie.pmml.models.scorecard.model.KiePMMLCharacteristic) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) Expression(com.github.javaparser.ast.expr.Expression) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) KiePMMLInternalException(org.kie.pmml.api.exceptions.KiePMMLInternalException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 79 with NodeList

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

the class KiePMMLCharacteristicFactory method getCharacteristicVariableDeclaration.

static BlockStmt getCharacteristicVariableDeclaration(final String variableName, final Characteristic characteristic, final List<Field<?>> fields) {
    final MethodDeclaration methodDeclaration = CHARACTERISTIC_TEMPLATE.getMethodsByName(GETKIEPMMLCHARACTERISTIC).get(0).clone();
    final BlockStmt characteristicBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration)));
    final VariableDeclarator variableDeclarator = getVariableDeclarator(characteristicBody, CHARACTERISTIC).orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, CHARACTERISTIC, characteristicBody)));
    variableDeclarator.setName(variableName);
    final BlockStmt toReturn = new BlockStmt();
    int counter = 0;
    NodeList<Expression> arguments = new NodeList<>();
    for (Attribute attribute : characteristic.getAttributes()) {
        String attributeVariableName = String.format(VARIABLE_NAME_TEMPLATE, variableName, counter);
        BlockStmt toAdd = getAttributeVariableDeclaration(attributeVariableName, attribute, fields);
        toAdd.getStatements().forEach(toReturn::addStatement);
        arguments.add(new NameExpr(attributeVariableName));
        counter++;
    }
    final MethodCallExpr initializer = variableDeclarator.getInitializer().orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, CHARACTERISTIC, characteristicBody))).asMethodCallExpr();
    final MethodCallExpr builder = getChainedMethodCallExprFrom("builder", initializer);
    builder.setArgument(0, new StringLiteralExpr(variableName));
    builder.setArgument(2, getArraysAsListInvocationMethodCall(arguments));
    getChainedMethodCallExprFrom("withBaselineScore", initializer).setArgument(0, getExpressionForObject(characteristic.getBaselineScore()));
    getChainedMethodCallExprFrom("withReasonCode", initializer).setArgument(0, getExpressionForObject(characteristic.getReasonCode()));
    characteristicBody.getStatements().forEach(toReturn::addStatement);
    return toReturn;
}
Also used : Attribute(org.dmg.pmml.scorecard.Attribute) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NodeList(com.github.javaparser.ast.NodeList) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) CommonCodegenUtils.getVariableDeclarator(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator) Expression(com.github.javaparser.ast.expr.Expression) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 80 with NodeList

use of com.github.javaparser.ast.NodeList in project checker-framework by typetools.

the class AnnotationFileParser method processTypeDecl.

/**
 * Process a type declaration: copy its annotations to {@code #annotationFileAnnos}.
 *
 * <p>This method stores the declaration's type parameters in {@link #typeParameters}. When
 * processing an ajava file, where traversal is handled externaly by a {@link
 * org.checkerframework.framework.ajava.JointJavacJavaParserVisitor}, these type variables must be
 * removed after processing the type's members. Otherwise, this method removes them.
 *
 * @param typeDecl the type declaration to process
 * @param outertypeName the name of the containing class, when processing a nested class;
 *     otherwise null
 * @param classTree the tree corresponding to typeDecl if processing an ajava file, null otherwise
 * @return a list of types variables for {@code typeDecl}. Only non-null if processing an ajava
 *     file, in which case the contents should be removed from {@link #typeParameters} after
 *     processing the type declaration's members
 */
private List<AnnotatedTypeVariable> processTypeDecl(TypeDeclaration<?> typeDecl, String outertypeName, @Nullable ClassTree classTree) {
    assert typeBeingParsed != null;
    if (skipNode(typeDecl)) {
        return null;
    }
    String innerName;
    @FullyQualifiedName String fqTypeName;
    TypeElement typeElt;
    if (classTree != null) {
        typeElt = TreeUtils.elementFromDeclaration(classTree);
        innerName = typeElt.getQualifiedName().toString();
        typeBeingParsed = new FqName(typeBeingParsed.packageName, innerName);
        fqTypeName = typeBeingParsed.toString();
    } else {
        String packagePrefix = outertypeName == null ? "" : outertypeName + ".";
        innerName = packagePrefix + typeDecl.getNameAsString();
        typeBeingParsed = new FqName(typeBeingParsed.packageName, innerName);
        fqTypeName = typeBeingParsed.toString();
        typeElt = elements.getTypeElement(fqTypeName);
    }
    if (!isAnnotatedForThisChecker(typeDecl.getAnnotations())) {
        return null;
    }
    if (typeElt == null) {
        if (debugAnnotationFileParser || (!warnIfNotFoundIgnoresClasses && !hasNoAnnotationFileParserWarning(typeDecl.getAnnotations()) && !hasNoAnnotationFileParserWarning(packageAnnos))) {
            if (elements.getAllTypeElements(fqTypeName).isEmpty()) {
                stubWarnNotFound(typeDecl, "Type not found: " + fqTypeName);
            } else {
                stubWarnNotFound(typeDecl, "Type not found uniquely: " + fqTypeName + " : " + elements.getAllTypeElements(fqTypeName));
            }
        }
        return null;
    }
    List<AnnotatedTypeVariable> typeDeclTypeParameters = null;
    if (typeElt.getKind() == ElementKind.ENUM) {
        if (!(typeDecl instanceof EnumDeclaration)) {
            warn(typeDecl, innerName + " is an enum, but stub file declared it as " + typeDecl.toString().split("\\R", 2)[0] + "...");
            return null;
        }
        typeDeclTypeParameters = processEnum((EnumDeclaration) typeDecl, typeElt);
        typeParameters.addAll(typeDeclTypeParameters);
    } else if (typeElt.getKind() == ElementKind.ANNOTATION_TYPE) {
        if (!(typeDecl instanceof AnnotationDeclaration)) {
            warn(typeDecl, innerName + " is an annotation, but stub file declared it as " + typeDecl.toString().split("\\R", 2)[0] + "...");
            return null;
        }
        stubWarnNotFound(typeDecl, "Skipping annotation type: " + fqTypeName);
    } else if (typeDecl instanceof ClassOrInterfaceDeclaration) {
        if (!(typeDecl instanceof ClassOrInterfaceDeclaration)) {
            warn(typeDecl, innerName + " is a class or interface, but stub file declared it as " + typeDecl.toString().split("\\R", 2)[0] + "...");
            return null;
        }
        typeDeclTypeParameters = processType(typeDecl, typeElt);
        typeParameters.addAll(typeDeclTypeParameters);
    } else if (typeDecl instanceof RecordDeclaration) {
        typeDeclTypeParameters = processType(typeDecl, typeElt);
        typeParameters.addAll(typeDeclTypeParameters);
    }
    // of this method.
    if (fileType == AnnotationFileType.AJAVA) {
        return typeDeclTypeParameters;
    }
    if (typeDecl instanceof RecordDeclaration) {
        NodeList<Parameter> recordMembers = ((RecordDeclaration) typeDecl).getParameters();
        LinkedHashMap<String, RecordComponentStub> byName = new LinkedHashMap<>();
        for (Parameter recordMember : recordMembers) {
            RecordComponentStub stub = processRecordField(recordMember, findFieldElement(typeElt, recordMember.getNameAsString(), recordMember));
            byName.put(recordMember.getNameAsString(), stub);
        }
        annotationFileAnnos.records.put(typeDecl.getFullyQualifiedName().get(), new RecordStub(byName));
    }
    Pair<Map<Element, BodyDeclaration<?>>, Map<Element, List<BodyDeclaration<?>>>> members = getMembers(typeDecl, typeElt, typeDecl);
    for (Map.Entry<Element, BodyDeclaration<?>> entry : members.first.entrySet()) {
        final Element elt = entry.getKey();
        final BodyDeclaration<?> decl = entry.getValue();
        switch(elt.getKind()) {
            case FIELD:
                processField((FieldDeclaration) decl, (VariableElement) elt);
                break;
            case ENUM_CONSTANT:
                // the TRACKER enum constant annotated with DefaultType:
                if (decl instanceof FieldDeclaration) {
                    processField((FieldDeclaration) decl, (VariableElement) elt);
                } else if (decl instanceof EnumConstantDeclaration) {
                    processEnumConstant((EnumConstantDeclaration) decl, (VariableElement) elt);
                } else {
                    throw new BugInCF("Unexpected decl type " + decl.getClass() + " for ENUM_CONSTANT kind, original: " + decl);
                }
                break;
            case CONSTRUCTOR:
            case METHOD:
                processCallableDeclaration((CallableDeclaration<?>) decl, (ExecutableElement) elt);
                break;
            case CLASS:
            case INTERFACE:
                // Not processing an ajava file, so ignore the return value.
                processTypeDecl((ClassOrInterfaceDeclaration) decl, innerName, null);
                break;
            case ENUM:
                // Not processing an ajava file, so ignore the return value.
                processTypeDecl((EnumDeclaration) decl, innerName, null);
                break;
            default:
                /* do nothing */
                stubWarnNotFound(decl, "AnnotationFileParser ignoring: " + elt);
                break;
        }
    }
    for (Map.Entry<Element, List<BodyDeclaration<?>>> entry : members.second.entrySet()) {
        ExecutableElement fakeOverridden = (ExecutableElement) entry.getKey();
        List<BodyDeclaration<?>> fakeOverrideDecls = entry.getValue();
        for (BodyDeclaration<?> bodyDecl : fakeOverrideDecls) {
            processFakeOverride(fakeOverridden, (CallableDeclaration<?>) bodyDecl, typeElt);
        }
    }
    if (typeDeclTypeParameters != null) {
        typeParameters.removeAll(typeDeclTypeParameters);
    }
    return null;
}
Also used : ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) FullyQualifiedName(org.checkerframework.checker.signature.qual.FullyQualifiedName) VariableElement(javax.lang.model.element.VariableElement) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) LinkedHashMap(java.util.LinkedHashMap) EnumConstantDeclaration(com.github.javaparser.ast.body.EnumConstantDeclaration) ArrayList(java.util.ArrayList) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) TypeElement(javax.lang.model.element.TypeElement) BugInCF(org.checkerframework.javacutil.BugInCF) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) RecordDeclaration(com.github.javaparser.ast.body.RecordDeclaration) AnnotationDeclaration(com.github.javaparser.ast.body.AnnotationDeclaration) ReceiverParameter(com.github.javaparser.ast.body.ReceiverParameter) Parameter(com.github.javaparser.ast.body.Parameter) TypeParameter(com.github.javaparser.ast.type.TypeParameter) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Aggregations

NodeList (com.github.javaparser.ast.NodeList)83 Expression (com.github.javaparser.ast.expr.Expression)48 NameExpr (com.github.javaparser.ast.expr.NameExpr)40 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)37 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)36 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)29 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)25 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)24 List (java.util.List)22 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)18 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)18 CompilationUnit (com.github.javaparser.ast.CompilationUnit)17 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)17 ArrayList (java.util.ArrayList)17 Collectors (java.util.stream.Collectors)17 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)16 ExpressionStmt (com.github.javaparser.ast.stmt.ExpressionStmt)16 Parameter (com.github.javaparser.ast.body.Parameter)15 Test (org.junit.Test)15 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)14