Search in sources :

Example 1 with CallableDeclaration

use of com.github.javaparser.ast.body.CallableDeclaration in project structr by structr.

the class JavaParserModule method parseJavaFilesAndSolveTypes.

private void parseJavaFilesAndSolveTypes(final Folder folder) {
    if (ignoreTests && "test".equals(folder.getName())) {
        return;
    }
    for (final File file : folder.getFiles()) {
        if (file.getContentType().equals("text/x-java")) {
            final String javaFileName = file.getName();
            if (javaFileName.equals("package-info.java") || javaFileName.equals("testPackage-info.java")) {
            } else {
                final String javaContent = file.getFavoriteContent();
                ClassOrInterface clsOrIface = null;
                CompilationUnit cu = null;
                try {
                    cu = JavaParser.parse(javaContent);
                    for (final TypeDeclaration type : cu.findAll(TypeDeclaration.class)) {
                        SymbolReference<? extends ResolvedValueDeclaration> decl = facade.solve(type.getName());
                        if (type.isClassOrInterfaceDeclaration()) {
                            org.structr.javaparser.entity.Package pkg = null;
                            if (cu.getPackageDeclaration().isPresent()) {
                                pkg = handlePackage(cu.getPackageDeclaration().get());
                            }
                            clsOrIface = handleClassOrInterface(type, pkg);
                        }
                    }
                    for (final BodyDeclaration t : cu.findAll(BodyDeclaration.class)) {
                        if (t instanceof CallableDeclaration) {
                            final CallableDeclaration callable = t.asCallableDeclaration();
                            if (t instanceof ConstructorDeclaration) {
                            // final ConstructorDeclaration cd = t.asConstructorDeclaration();
                            // logger.info("Constructor found: " + cd.getNameAsString());
                            // 
                            // final SymbolReference<ResolvedReferenceTypeDeclaration> constructorRef = typeSolver.tryToSolveType(cd.getNameAsString());
                            // if (constructorRef.isSolved()) {
                            // 
                            // logger.info("Solved constructor: " + cd.getNameAsString());
                            // //final ResolvedReferenceTypeDeclaration decl = constructorRef.getCorrespondingDeclaration();
                            // }
                            } else if (t instanceof MethodDeclaration) {
                                final MethodDeclaration md = t.asMethodDeclaration();
                                final String methodName = md.getNameAsString();
                                logger.info("Method found: " + methodName);
                                // Create methods and link to class
                                final PropertyMap identifyingMethodProperties = new PropertyMap();
                                identifyingMethodProperties.put(Method.name, methodName);
                                final PropertyMap methodProperties = new PropertyMap();
                                methodProperties.putAll(identifyingMethodProperties);
                                methodProperties.put(Method.classOrInterface, clsOrIface);
                                methodProperties.put(Method.declaration, md.getDeclarationAsString());
                                final Optional<BlockStmt> block = md.getBody();
                                if (block.isPresent()) {
                                    methodProperties.put(Method.body, block.get().toString());
                                }
                                final String symbolName = StringUtils.substringAfterLast(clsOrIface.getName(), ".") + "." + md.getNameAsString();
                                try {
                                    final SymbolReference<? extends ResolvedValueDeclaration> methodRef = facade.solve(md.getName());
                                    if (methodRef.isSolved()) {
                                        final ResolvedValueDeclaration decl = methodRef.getCorrespondingDeclaration();
                                        if (decl.isMethod()) {
                                            final String mName = decl.asMethod().getName();
                                            final String signature = decl.asMethod().getSignature();
                                            logger.info("Solved method: " + methodRef.toString() + ", signature: " + signature);
                                            methodProperties.put(Method.resolved, true);
                                        }
                                    }
                                } catch (final UnsolvedSymbolException ignore) {
                                }
                                getOrCreate(Method.class, identifyingMethodProperties, methodProperties);
                                logger.info("Created (or found) method " + symbolName);
                            }
                        // final NodeList<Parameter> parameters = callable.getParameters();
                        // 
                        // List<JsonResult> parameterList = new ArrayList<>();
                        // 
                        // parameters.forEach((p) -> {
                        // 
                        // JsonResult param = new JsonResult();
                        // 
                        // param.addName(p);
                        // param.addType(p.getType());
                        // param.addModifiers(p);
                        // 
                        // parameterList.add(param);
                        // });
                        }
                    }
                } catch (Throwable ignore) {
                }
            }
        }
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) UnsolvedSymbolException(com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException) ClassOrInterface(org.structr.javaparser.entity.ClassOrInterface) Package(org.structr.javaparser.entity.Package) Optional(java.util.Optional) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Method(org.structr.javaparser.entity.Method) PropertyMap(org.structr.core.property.PropertyMap) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) File(org.structr.web.entity.File) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Example 2 with CallableDeclaration

use of com.github.javaparser.ast.body.CallableDeclaration in project structr by structr.

the class JavaParserModule method toJson.

private JsonResult toJson(final CompilationUnit cu) {
    final JsonResult jsonResult = new JsonResult();
    final NodeList<TypeDeclaration<?>> types = cu.getTypes();
    if (types.isEmpty()) {
        return jsonResult;
    }
    final TypeDeclaration<?> type = types.get(0);
    jsonResult.addName(type);
    jsonResult.addModifiers(type);
    final Optional<PackageDeclaration> pkg = cu.getPackageDeclaration();
    if (pkg.isPresent()) {
        jsonResult.addPackage(pkg.get());
    }
    final List<BodyDeclaration<?>> members = type.getMembers();
    final List<JsonResult> membersList = new ArrayList<>();
    members.forEach((t) -> {
        final JsonResult member = new JsonResult();
        if (t instanceof FieldDeclaration) {
            final FieldDeclaration fd = t.asFieldDeclaration();
            member.addName(fd.getVariable(0));
            member.addType(fd.getVariable(0).getType());
            member.addModifiers(fd);
        } else if (t instanceof CallableDeclaration) {
            final CallableDeclaration callable = t.asCallableDeclaration();
            if (t instanceof ConstructorDeclaration) {
                final ConstructorDeclaration cd = t.asConstructorDeclaration();
                member.addName(cd);
                member.isConstructor();
                member.addModifiers(cd);
            } else if (t instanceof MethodDeclaration) {
                final MethodDeclaration md = t.asMethodDeclaration();
                member.addName(md);
                member.isMethod();
                member.addReturnType(md.getType());
                member.addModifiers(md);
                member.addBody(md);
            }
            final NodeList<Parameter> parameters = callable.getParameters();
            List<JsonResult> parameterList = new ArrayList<>();
            parameters.forEach((p) -> {
                JsonResult param = new JsonResult();
                param.addName(p);
                param.addType(p.getType());
                param.addModifiers(p);
                parameterList.add(param);
            });
            member.addParameters(parameterList);
        }
        membersList.add(member);
    });
    jsonResult.addMembers(membersList);
    return jsonResult;
}
Also used : JsonObject(com.google.gson.JsonObject) Package(org.structr.javaparser.entity.Package) XPathExpressionException(javax.xml.xpath.XPathExpressionException) UnsolvedSymbolException(com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException) LoggerFactory(org.slf4j.LoggerFactory) SecurityContext(org.structr.common.SecurityContext) StringUtils(org.apache.commons.lang3.StringUtils) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Actions(org.structr.schema.action.Actions) FrameworkException(org.structr.common.error.FrameworkException) App(org.structr.core.app.App) NodeWithSimpleName(com.github.javaparser.ast.nodeTypes.NodeWithSimpleName) Type(com.github.javaparser.ast.type.Type) Document(org.w3c.dom.Document) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaInterface(org.structr.javaparser.entity.JavaInterface) NodeList(com.github.javaparser.ast.NodeList) Folder(org.structr.web.entity.Folder) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Set(java.util.Set) GraphObject(org.structr.core.GraphObject) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) Functions(org.structr.core.function.Functions) JsonArray(com.google.gson.JsonArray) List(java.util.List) StructrModule(org.structr.module.StructrModule) JarTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver) SAXException(org.xml.sax.SAXException) LicenseManager(org.structr.api.service.LicenseManager) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) QName(javax.xml.namespace.QName) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeWithOptionalBlockStmt(com.github.javaparser.ast.nodeTypes.NodeWithOptionalBlockStmt) StructrApp(org.structr.core.app.StructrApp) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) Method(org.structr.javaparser.entity.Method) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration) XPath(javax.xml.xpath.XPath) XPathConstants(javax.xml.xpath.XPathConstants) Parameter(com.github.javaparser.ast.body.Parameter) HashMap(java.util.HashMap) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) ArrayList(java.util.ArrayList) PropertyMap(org.structr.core.property.PropertyMap) File(org.structr.web.entity.File) JavaClass(org.structr.javaparser.entity.JavaClass) JsonPrimitive(com.google.gson.JsonPrimitive) ClassOrInterface(org.structr.javaparser.entity.ClassOrInterface) LinkedHashSet(java.util.LinkedHashSet) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeWithModifiers(com.github.javaparser.ast.nodeTypes.NodeWithModifiers) Files(java.nio.file.Files) AbstractSchemaNode(org.structr.core.entity.AbstractSchemaNode) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) AddJarsToIndexFunction(org.structr.javaparser.entity.AddJarsToIndexFunction) AtomicLong(java.util.concurrent.atomic.AtomicLong) XPathFactory(javax.xml.xpath.XPathFactory) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) StringReader(java.io.StringReader) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Paths(java.nio.file.Paths) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) Module(org.structr.javaparser.entity.Module) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) NodeList(com.github.javaparser.ast.NodeList) ArrayList(java.util.ArrayList) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) ArrayList(java.util.ArrayList) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration)

Example 3 with CallableDeclaration

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

the class WholeProgramInferenceJavaParserStorage method createWrappersForClass.

/**
 * The first two arugments are a javac tree and a JavaParser node representing the same class.
 * This method creates wrappers around all the classes, fields, and methods in that class, and
 * stores those wrappers in {@code sourceAnnos}.
 *
 * @param javacClass javac tree for class
 * @param javaParserClass JavaParser node corresponding to the same class as {@code javacClass}
 * @param sourceAnnos compilation unit wrapper to add new wrappers to
 */
private void createWrappersForClass(ClassTree javacClass, TypeDeclaration<?> javaParserClass, CompilationUnitAnnos sourceAnnos) {
    JointJavacJavaParserVisitor visitor = new DefaultJointVisitor() {

        @Override
        public void processClass(ClassTree javacTree, ClassOrInterfaceDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processClass(ClassTree javacTree, EnumDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processClass(ClassTree javacTree, RecordDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processNewClass(NewClassTree javacTree, ObjectCreationExpr javaParserNode) {
            if (javacTree.getClassBody() != null) {
                addClass(javacTree.getClassBody());
            }
        }

        /**
         * Creates a wrapper around the class for {@code tree} and stores it in {@code
         * sourceAnnos}.
         *
         * @param tree tree to add
         */
        private void addClass(ClassTree tree) {
            TypeElement classElt = TreeUtils.elementFromDeclaration(tree);
            String className = ElementUtils.getBinaryName(classElt);
            ClassOrInterfaceAnnos typeWrapper = new ClassOrInterfaceAnnos();
            if (!classToAnnos.containsKey(className)) {
                classToAnnos.put(className, typeWrapper);
            }
            sourceAnnos.types.add(typeWrapper);
        }

        @Override
        public void processMethod(MethodTree javacTree, MethodDeclaration javaParserNode) {
            addCallableDeclaration(javacTree, javaParserNode);
        }

        @Override
        public void processMethod(MethodTree javacTree, ConstructorDeclaration javaParserNode) {
            addCallableDeclaration(javacTree, javaParserNode);
        }

        /**
         * Creates a wrapper around {@code javacTree} with the corresponding declaration {@code
         * javaParserNode} and stores it in {@code sourceAnnos}.
         *
         * @param javacTree javac tree for declaration to add
         * @param javaParserNode JavaParser node for the same class as {@code javacTree}
         */
        private void addCallableDeclaration(MethodTree javacTree, CallableDeclaration<?> javaParserNode) {
            ExecutableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            String className = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(className);
            String executableSignature = JVMNames.getJVMMethodSignature(javacTree);
            if (!enclosingClass.callableDeclarations.containsKey(executableSignature)) {
                enclosingClass.callableDeclarations.put(executableSignature, new CallableDeclarationAnnos(javaParserNode));
            }
        }

        @Override
        public void processVariable(VariableTree javacTree, EnumConstantDeclaration javaParserNode) {
            VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            if (!elt.getKind().isField()) {
                throw new BugInCF(elt + " is not a field but a " + elt.getKind());
            }
            String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
            String fieldName = javacTree.getName().toString();
            enclosingClass.enumConstants.add(fieldName);
            // Ensure that if an enum constant defines a class, that class gets registered properly.
            // See e.g. https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.1 for
            // the specification of an enum constant, which does permit it to define an anonymous
            // class.
            NewClassTree constructor = (NewClassTree) javacTree.getInitializer();
            if (constructor.getClassBody() != null) {
                addClass(constructor.getClassBody());
            }
        }

        @Override
        public void processVariable(VariableTree javacTree, VariableDeclarator javaParserNode) {
            // below call to TreeUtils.elementFromDeclaration causes a crash.
            if (TreeUtils.elementFromTree(javacTree) == null) {
                return;
            }
            VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            if (!elt.getKind().isField()) {
                return;
            }
            String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
            String fieldName = javacTree.getName().toString();
            if (!enclosingClass.fields.containsKey(fieldName)) {
                enclosingClass.fields.put(fieldName, new FieldAnnos(javaParserNode));
            }
        }
    };
    visitor.visitClass(javacClass, javaParserClass);
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodTree(com.sun.source.tree.MethodTree) TypeElement(javax.lang.model.element.TypeElement) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ExecutableElement(javax.lang.model.element.ExecutableElement) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) VariableElement(javax.lang.model.element.VariableElement) BugInCF(org.checkerframework.javacutil.BugInCF) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) RecordDeclaration(com.github.javaparser.ast.body.RecordDeclaration) EnumConstantDeclaration(com.github.javaparser.ast.body.EnumConstantDeclaration) JointJavacJavaParserVisitor(org.checkerframework.framework.ajava.JointJavacJavaParserVisitor) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) DefaultJointVisitor(org.checkerframework.framework.ajava.DefaultJointVisitor)

Aggregations

CallableDeclaration (com.github.javaparser.ast.body.CallableDeclaration)3 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)3 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)3 CompilationUnit (com.github.javaparser.ast.CompilationUnit)2 BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)2 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)2 ResolvedValueDeclaration (com.github.javaparser.resolution.declarations.ResolvedValueDeclaration)2 UnsolvedSymbolException (com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException)2 SymbolReference (com.github.javaparser.symbolsolver.model.resolution.SymbolReference)2 Optional (java.util.Optional)2 PropertyMap (org.structr.core.property.PropertyMap)2 ClassOrInterface (org.structr.javaparser.entity.ClassOrInterface)2 Method (org.structr.javaparser.entity.Method)2 Package (org.structr.javaparser.entity.Package)2 File (org.structr.web.entity.File)2 JavaParser (com.github.javaparser.JavaParser)1 NodeList (com.github.javaparser.ast.NodeList)1 PackageDeclaration (com.github.javaparser.ast.PackageDeclaration)1 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)1 EnumConstantDeclaration (com.github.javaparser.ast.body.EnumConstantDeclaration)1