Search in sources :

Example 26 with BodyDeclaration

use of com.github.javaparser.ast.body.BodyDeclaration in project butterknife by JakeWharton.

the class FinalRClassBuilder method addResourceType.

private static void addResourceType(List<String> supportedTypes, TypeSpec.Builder result, ClassOrInterfaceDeclaration node) {
    if (!supportedTypes.contains(node.getNameAsString())) {
        return;
    }
    String type = node.getNameAsString();
    TypeSpec.Builder resourceType = TypeSpec.classBuilder(type).addModifiers(PUBLIC, STATIC, FINAL);
    for (BodyDeclaration field : node.getMembers()) {
        if (field instanceof FieldDeclaration) {
            FieldDeclaration declaration = (FieldDeclaration) field;
            // used in annotations.
            if (isInt(declaration)) {
                addResourceField(resourceType, declaration.getVariables().get(0), getSupportAnnotationClass(type));
            }
        }
    }
    result.addType(resourceType.build());
}
Also used : BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 27 with BodyDeclaration

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

the class CommonCodegenUtilsTest method populateMethodDeclarations.

@Test
public void populateMethodDeclarations() {
    final List<MethodDeclaration> toAdd = IntStream.range(0, 5).boxed().map(index -> getMethodDeclaration("METHOD_" + index)).collect(Collectors.toList());
    final ClassOrInterfaceDeclaration toPopulate = new ClassOrInterfaceDeclaration();
    assertTrue(toPopulate.getMembers().isEmpty());
    CommonCodegenUtils.populateMethodDeclarations(toPopulate, toAdd);
    final NodeList<BodyDeclaration<?>> retrieved = toPopulate.getMembers();
    assertEquals(toAdd.size(), retrieved.size());
    assertTrue(toAdd.stream().anyMatch(methodDeclaration -> retrieved.stream().anyMatch(bodyDeclaration -> bodyDeclaration.equals(methodDeclaration))));
}
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) CommonCodegenUtils.literalExprFrom(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.literalExprFrom) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) KiePMMLNameValue(org.kie.pmml.commons.model.tuples.KiePMMLNameValue) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) Node(com.github.javaparser.ast.Node) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) 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) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) LongLiteralExpr(com.github.javaparser.ast.expr.LongLiteralExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) IntStream(java.util.stream.IntStream) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) Parameter(com.github.javaparser.ast.body.Parameter) Assert.assertThrows(org.junit.Assert.assertThrows) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Assert.assertSame(org.junit.Assert.assertSame) DoubleLiteralExpr(com.github.javaparser.ast.expr.DoubleLiteralExpr) OPTIONAL_FILTERED_KIEPMMLNAMEVALUE_NAME(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.OPTIONAL_FILTERED_KIEPMMLNAMEVALUE_NAME) StaticJavaParser.parseBlock(com.github.javaparser.StaticJavaParser.parseBlock) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) Assert.assertNotNull(org.junit.Assert.assertNotNull) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) CodegenTestUtils.commonValidateCompilation(org.kie.pmml.compiler.commons.testutils.CodegenTestUtils.commonValidateCompilation) NameExpr(com.github.javaparser.ast.expr.NameExpr) Statement(com.github.javaparser.ast.stmt.Statement) DATA_TYPE(org.kie.pmml.api.enums.DATA_TYPE) LAMBDA_PARAMETER_NAME(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.LAMBDA_PARAMETER_NAME) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Collections(java.util.Collections) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) IntegerLiteralExpr(com.github.javaparser.ast.expr.IntegerLiteralExpr) Assert.assertEquals(org.junit.Assert.assertEquals) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) Test(org.junit.Test)

Example 28 with BodyDeclaration

use of com.github.javaparser.ast.body.BodyDeclaration 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)

Example 29 with BodyDeclaration

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

the class AnnotationFileParser method getMembers.

/**
 * Returns a pair of mappings. For each member declaration of the JavaParser type declaration
 * {@code typeDecl}:
 *
 * <ul>
 *   <li>If {@code typeElt} contains a member element for it, the first mapping maps the member
 *       element to it.
 *   <li>If it is a fake override, the second mapping maps each element it overrides to it.
 *   <li>Otherwise, does nothing.
 * </ul>
 *
 * This method does not read or write the field {@link #annotationFileAnnos}.
 *
 * @param typeDecl a JavaParser type declaration
 * @param typeElt the javac element for {@code typeDecl}
 * @return two mappings: from javac elements to their JavaParser declaration, and from javac
 *     elements to fake overrides of them
 * @param astNode where to report errors
 */
private Pair<Map<Element, BodyDeclaration<?>>, Map<Element, List<BodyDeclaration<?>>>> getMembers(TypeDeclaration<?> typeDecl, TypeElement typeElt, NodeWithRange<?> astNode) {
    assert (typeElt.getSimpleName().contentEquals(typeDecl.getNameAsString()) || typeDecl.getNameAsString().endsWith("$" + typeElt.getSimpleName())) : String.format("%s  %s", typeElt.getSimpleName(), typeDecl.getName());
    Map<Element, BodyDeclaration<?>> elementsToDecl = new LinkedHashMap<>();
    Map<Element, List<BodyDeclaration<?>>> fakeOverrideDecls = new LinkedHashMap<>();
    for (BodyDeclaration<?> member : typeDecl.getMembers()) {
        putNewElement(elementsToDecl, fakeOverrideDecls, typeElt, member, typeDecl.getNameAsString(), astNode);
    }
    // For an enum type declaration, also add the enum constants
    if (typeDecl instanceof EnumDeclaration) {
        EnumDeclaration enumDecl = (EnumDeclaration) typeDecl;
        // getEntries() gives the list of enum constant declarations
        for (BodyDeclaration<?> member : enumDecl.getEntries()) {
            putNewElement(elementsToDecl, fakeOverrideDecls, typeElt, member, typeDecl.getNameAsString(), astNode);
        }
    }
    return Pair.of(elementsToDecl, fakeOverrideDecls);
}
Also used : 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) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) ArrayList(java.util.ArrayList) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration)

Aggregations

BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)29 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)10 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)9 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)9 CompilationUnit (com.github.javaparser.ast.CompilationUnit)7 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)7 EnumDeclaration (com.github.javaparser.ast.body.EnumDeclaration)7 NodeList (com.github.javaparser.ast.NodeList)6 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)6 ArrayList (java.util.ArrayList)6 EnumConstantDeclaration (com.github.javaparser.ast.body.EnumConstantDeclaration)5 BlockComment (com.github.javaparser.ast.comments.BlockComment)5 Comment (com.github.javaparser.ast.comments.Comment)5 JavadocComment (com.github.javaparser.ast.comments.JavadocComment)5 LineComment (com.github.javaparser.ast.comments.LineComment)5 List (java.util.List)5 Parameter (com.github.javaparser.ast.body.Parameter)4 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)3 Expression (com.github.javaparser.ast.expr.Expression)3 Type (com.github.javaparser.ast.type.Type)3