Search in sources :

Example 6 with CompilationUnit

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

the class StubParser method getAllStubAnnotations.

/**
 * Returns all annotations found in the stub file, as a value for {@link #allStubAnnotations}.
 * Note that this also modifies {@link #importedConstants} and {@link #importedTypes}.
 *
 * @see #allStubAnnotations
 */
private Map<String, AnnotationMirror> getAllStubAnnotations() {
    Map<String, AnnotationMirror> result = new HashMap<>();
    assert !stubUnit.getCompilationUnits().isEmpty();
    CompilationUnit cu = stubUnit.getCompilationUnits().get(0);
    if (cu.getImports() == null) {
        return result;
    }
    for (ImportDeclaration importDecl : cu.getImports()) {
        String imported = importDecl.getNameAsString();
        try {
            if (importDecl.isAsterisk()) {
                if (importDecl.isStatic()) {
                    // Wildcard import of members of a type (class or interface)
                    TypeElement element = getTypeElement(imported, "Imported type not found");
                    if (element != null) {
                        // Find nested annotations
                        // Find compile time constant fields, or values of an enum
                        putAllNew(result, annosInType(element));
                        importedConstants.addAll(getImportableMembers(element));
                        addEnclosingTypesToImportedTypes(element);
                    }
                } else {
                    // Wildcard import of members of a package
                    PackageElement element = findPackage(imported);
                    if (element != null) {
                        putAllNew(result, annosInPackage(element));
                        addEnclosingTypesToImportedTypes(element);
                    }
                }
            } else {
                // A single (non-wildcard) import
                final TypeElement importType = elements.getTypeElement(imported);
                if (importType == null && !importDecl.isStatic()) {
                    // Class or nested class (according to JSL), but we can't resolve
                    stubWarnNotFound("Imported type not found: " + imported);
                } else if (importType == null) {
                    // Nested Field
                    Pair<String, String> typeParts = StubUtil.partitionQualifiedName(imported);
                    String type = typeParts.first;
                    String fieldName = typeParts.second;
                    TypeElement enclType = getTypeElement(type, String.format("Enclosing type of static field %s not found", fieldName));
                    if (enclType != null) {
                        if (findFieldElement(enclType, fieldName) != null) {
                            importedConstants.add(imported);
                        }
                    }
                } else if (importType.getKind() == ElementKind.ANNOTATION_TYPE) {
                    // Single annotation or nested annotation
                    AnnotationMirror anno = AnnotationBuilder.fromName(elements, imported);
                    if (anno != null) {
                        Element annoElt = anno.getAnnotationType().asElement();
                        putNoOverride(result, annoElt.getSimpleName().toString(), anno);
                        importedTypes.put(annoElt.getSimpleName().toString(), (TypeElement) annoElt);
                    } else {
                        stubWarnNotFound("Could not load import: " + imported);
                    }
                } else {
                    // Class or nested class
                    // TODO: Is this needed?
                    importedConstants.add(imported);
                    TypeElement element = getTypeElement(imported, "Imported type not found");
                    importedTypes.put(element.getSimpleName().toString(), element);
                }
            }
        } catch (AssertionError error) {
            stubWarnNotFound("" + error);
        }
    }
    return result;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) AnnotationMirror(javax.lang.model.element.AnnotationMirror) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TypeElement(javax.lang.model.element.TypeElement) 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) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) PackageElement(javax.lang.model.element.PackageElement) Pair(org.checkerframework.javacutil.Pair) MemberValuePair(com.github.javaparser.ast.expr.MemberValuePair)

Example 7 with CompilationUnit

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

the class StubUtil method findDeclaration.

/*package-scope*/
static TypeDeclaration<?> findDeclaration(String className, StubUnit indexFile) {
    int indexOfDot = className.lastIndexOf('.');
    if (indexOfDot == -1) {
        // classes not within a package needs to be the first in the index file
        assert !indexFile.getCompilationUnits().isEmpty();
        assert indexFile.getCompilationUnits().get(0).getPackageDeclaration() == null;
        return findDeclaration(className, indexFile.getCompilationUnits().get(0));
    }
    final String packageName = className.substring(0, indexOfDot);
    final String simpleName = className.substring(indexOfDot + 1);
    for (CompilationUnit cu : indexFile.getCompilationUnits()) {
        if (cu.getPackageDeclaration().isPresent() && cu.getPackageDeclaration().get().getNameAsString().equals(packageName)) {
            TypeDeclaration<?> type = findDeclaration(simpleName, cu);
            if (type != null) {
                return type;
            }
        }
    }
    // Couldn't find it
    return null;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit)

Example 8 with CompilationUnit

use of com.github.javaparser.ast.CompilationUnit in project activityinfo by bedatadriven.

the class Pull method updateJavaSource.

/**
 * Updates the @DefaultMessage/@DefaultStringValue annotations and javadoc in the Messages or Constants
 * interface Java source file.
 */
private void updateJavaSource(ResourceClass resourceClass, TranslationSet translations) throws IOException {
    CompilationUnit compilationUnit;
    try {
        compilationUnit = resourceClass.parseJavaSource();
    } catch (Exception e) {
        throw new IOException("Failed to parse " + resourceClass.getJavaSourcePath(), e);
    }
    TranslationSet validated = validateMessages(resourceClass, compilationUnit, translations);
    DefaultUpdatingVisitor visitor = new DefaultUpdatingVisitor();
    visitor.visit(compilationUnit, validated);
    if (visitor.isDirty()) {
        try {
            Files.write(compilationUnit.toString(), resourceClass.getJavaSourceFile(), Charsets.UTF_8);
        } catch (IOException e) {
            throw new IOException("Failed to write updated source file to " + resourceClass.getJavaSourcePath(), e);
        }
        System.out.println("Updated default translations in " + resourceClass.getJavaSourcePath());
    } else {
        System.out.println(resourceClass.getClassName() + " is up to date.");
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) TranslationSet(org.activityinfo.i18n.tools.model.TranslationSet) DefaultUpdatingVisitor(org.activityinfo.i18n.tools.parser.DefaultUpdatingVisitor) IOException(java.io.IOException) IOException(java.io.IOException)

Example 9 with CompilationUnit

use of com.github.javaparser.ast.CompilationUnit in project activityinfo by bedatadriven.

the class ResourceClass method inspect.

public InspectingVisitor inspect() {
    // Extract keys from the resource file
    InspectingVisitor visitor = new InspectingVisitor(getJavaSourceFile().getName());
    try {
        CompilationUnit cu = parseJavaSource();
        visitor.visit(cu, null);
    } catch (Exception e) {
        throw new RuntimeException("Exception parsing " + getJavaSourceFile() + ": " + e.getMessage(), e);
    }
    return visitor;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) InspectingVisitor(org.activityinfo.i18n.tools.parser.InspectingVisitor) ParseException(com.github.javaparser.ParseException)

Example 10 with CompilationUnit

use of com.github.javaparser.ast.CompilationUnit in project controller by opendaylight.

the class JMXGeneratorTest method verifyFile.

private static void verifyFile(final File file, final AbstractVerifier verifier) throws ParseException, IOException {
    final CompilationUnit cu = JavaParser.parse(file);
    cu.accept(verifier, null);
    verifier.verify();
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit)

Aggregations

CompilationUnit (com.github.javaparser.ast.CompilationUnit)489 Test (org.junit.Test)304 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)160 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)140 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)128 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)101 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)70 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)66 Context (com.github.javaparser.symbolsolver.core.resolution.Context)62 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)55 CompilationUnitContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext)51 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)45 File (java.io.File)39 Expression (com.github.javaparser.ast.expr.Expression)38 ClassOrInterfaceDeclarationContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.ClassOrInterfaceDeclarationContext)38 MethodUsage (com.github.javaparser.resolution.MethodUsage)34 MemoryTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.MemoryTypeSolver)33 AbstractTest (com.github.javaparser.symbolsolver.AbstractTest)29 CombinedTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver)29 ArrayList (java.util.ArrayList)29