Search in sources :

Example 6 with Project

use of meghanada.project.Project in project meghanada-server by mopemope.

the class CacheEventSubscriber method analyze.

private void analyze() {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    final Session session = super.sessionEventBus.getSession();
    final Project project = session.getCurrentProject();
    final CachedASMReflector reflector = CachedASMReflector.getInstance();
    reflector.addClasspath(project.getOutput());
    reflector.addClasspath(project.getTestOutput());
    project.getDependencies().stream().filter(pd -> pd.getType().equals(ProjectDependency.Type.PROJECT)).forEach(pd -> {
        final File df = new File(pd.getDependencyFilePath());
        if (df.exists() && df.isDirectory()) {
            reflector.addClasspath(df);
        }
    });
    final Collection<File> dependentJars = session.getDependentJars();
    final int size = dependentJars.size();
    timeItF("create class index ... read " + size + " jars. elapsed:{}", () -> {
        reflector.addClasspath(dependentJars);
        reflector.createClassIndexes();
    });
    if (cleanUnusedSource(project)) {
        project.resetCallerMap();
    }
    log.info("start analyze sources ...");
    timeItF("analyzed and compiled. elapsed:{}", () -> {
        try {
            final CompileResult compileResult = project.compileJava();
            if (compileResult.isSuccess()) {
                if (compileResult.hasDiagnostics()) {
                    log.warn("compile message: {}", compileResult.getDiagnosticsSummary());
                }
                final CompileResult testCompileResult = project.compileTestJava();
                if (testCompileResult.isSuccess()) {
                    if (testCompileResult.hasDiagnostics()) {
                        log.warn("compile(test) message: {}", testCompileResult.getDiagnosticsSummary());
                    }
                } else {
                    log.warn("compile(test) error: {}", testCompileResult.getDiagnosticsSummary());
                }
            } else {
                log.warn("compile message  {}", compileResult.getDiagnosticsSummary());
            }
        } catch (Exception e) {
            log.catching(e);
        }
    });
    final Runtime runtime = Runtime.getRuntime();
    final float maxMemory = runtime.maxMemory() / 1024 / 1024;
    final float totalMemory = runtime.totalMemory() / 1024 / 1024;
    final float usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
    log.info("class index size:{} total elapsed:{}", reflector.getGlobalClassIndex().size(), stopwatch.stop());
    Config.showMemory();
    log.info("Ready");
}
Also used : SessionEventBus(meghanada.session.SessionEventBus) Stopwatch(com.google.common.base.Stopwatch) Collection(java.util.Collection) CompileResult(meghanada.analyze.CompileResult) Config.timeItF(meghanada.config.Config.timeItF) ProjectDatabaseHelper(meghanada.store.ProjectDatabaseHelper) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) File(java.io.File) Session(meghanada.session.Session) Logger(org.apache.logging.log4j.Logger) Project(meghanada.project.Project) Subscribe(com.google.common.eventbus.Subscribe) ProjectDependency(meghanada.project.ProjectDependency) Config(meghanada.config.Config) LogManager(org.apache.logging.log4j.LogManager) Project(meghanada.project.Project) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) Stopwatch(com.google.common.base.Stopwatch) CompileResult(meghanada.analyze.CompileResult) File(java.io.File) Session(meghanada.session.Session)

Example 7 with Project

use of meghanada.project.Project in project meghanada-server by mopemope.

the class GradleProject method parseProject.

@Override
public Project parseProject() throws ProjectParseException {
    final ProjectConnection connection = getProjectConnection();
    log.info("loading gradle project:{}", new File(this.projectRoot, Project.GRADLE_PROJECT_FILE));
    try {
        BuildEnvironment env = connection.getModel(BuildEnvironment.class);
        String version = env.getGradle().getGradleVersion();
        if (isNull(version)) {
            version = GradleVersion.current().getVersion();
        }
        if (nonNull(version)) {
            this.gradleVersion = new ComparableVersion(version);
        }
        final IdeaProject ideaProject = debugTimeItF("get idea project model elapsed={}", () -> connection.getModel(IdeaProject.class));
        this.setCompileTarget(ideaProject);
        log.trace("load root project path:{}", this.rootProject);
        final DomainObjectSet<? extends IdeaModule> modules = ideaProject.getModules();
        final List<? extends IdeaModule> mainModules = modules.parallelStream().filter(ideaModule -> {
            final org.gradle.tooling.model.GradleProject gradleProject = ideaModule.getGradleProject();
            final File moduleProjectRoot = gradleProject.getProjectDirectory();
            final String name = ideaModule.getName();
            log.trace("find sub-module name {} path {} ", name, moduleProjectRoot);
            this.allModules.putIfAbsent(name, moduleProjectRoot);
            return moduleProjectRoot.equals(this.getProjectRoot());
        }).collect(Collectors.toList());
        mainModules.forEach(wrapIOConsumer(this::parseIdeaModule));
        // set default output
        if (isNull(super.output)) {
            String build = Joiner.on(File.separator).join(this.projectRoot, "build", "classes", "main");
            if (nonNull(gradleVersion) && gradleVersion.compareTo(new ComparableVersion("4.0")) >= 0) {
                build = Joiner.on(File.separator).join(this.projectRoot, "build", "classes", "java", "main");
            }
            super.output = this.normalize(build);
        }
        if (isNull(super.testOutput)) {
            String build = Joiner.on(File.separator).join(this.projectRoot, "build", "classes", "test");
            if (nonNull(gradleVersion) && gradleVersion.compareTo(new ComparableVersion("4.0")) >= 0) {
                build = Joiner.on(File.separator).join(this.projectRoot, "build", "classes", "java", "test");
            }
            super.testOutput = this.normalize(build);
        }
        return this;
    } catch (Exception e) {
        throw new ProjectParseException(e);
    } finally {
        connection.close();
    }
}
Also used : Config.debugTimeItF(meghanada.config.Config.debugTimeItF) IdeaDependency(org.gradle.tooling.model.idea.IdeaDependency) ProjectParseException(meghanada.project.ProjectParseException) IdeaJavaLanguageSettings(org.gradle.tooling.model.idea.IdeaJavaLanguageSettings) FunctionUtils.wrapIOConsumer(meghanada.utils.FunctionUtils.wrapIOConsumer) StringUtils(org.apache.commons.lang3.StringUtils) PipedInputStream(java.io.PipedInputStream) Map(java.util.Map) GradleConnector(org.gradle.tooling.GradleConnector) Objects.isNull(java.util.Objects.isNull) ComparableVersion(org.apache.maven.artifact.versioning.ComparableVersion) Splitter(com.google.common.base.Splitter) GradleVersion(org.gradle.util.GradleVersion) BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) BuildLauncher(org.gradle.tooling.BuildLauncher) CompileResult(meghanada.analyze.CompileResult) AndroidProject(com.android.builder.model.AndroidProject) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Collectors(java.util.stream.Collectors) ResultHandler(org.gradle.tooling.ResultHandler) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClassNameUtils(meghanada.utils.ClassNameUtils) IdeaContentRoot(org.gradle.tooling.model.idea.IdeaContentRoot) IdeaSingleEntryLibraryDependency(org.gradle.tooling.model.idea.IdeaSingleEntryLibraryDependency) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) Project(meghanada.project.Project) Objects.nonNull(java.util.Objects.nonNull) ProjectDependency(meghanada.project.ProjectDependency) Config(meghanada.config.Config) Joiner(com.google.common.base.Joiner) HashMap(java.util.HashMap) GradleConnectionException(org.gradle.tooling.GradleConnectionException) IdeaSourceDirectory(org.gradle.tooling.model.idea.IdeaSourceDirectory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) IdeaModule(org.gradle.tooling.model.idea.IdeaModule) Files(com.google.common.io.Files) ConfigFactory(com.typesafe.config.ConfigFactory) UnsupportedMethodException(org.gradle.tooling.model.UnsupportedMethodException) IdeaModuleDependency(org.gradle.tooling.model.idea.IdeaModuleDependency) DomainObjectSet(org.gradle.tooling.model.DomainObjectSet) IOException(java.io.IOException) PipedOutputStream(java.io.PipedOutputStream) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) IdeaProject(org.gradle.tooling.model.idea.IdeaProject) GradleModuleVersion(org.gradle.tooling.model.GradleModuleVersion) ProjectConnection(org.gradle.tooling.ProjectConnection) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) IdeaProject(org.gradle.tooling.model.idea.IdeaProject) ProjectConnection(org.gradle.tooling.ProjectConnection) ComparableVersion(org.apache.maven.artifact.versioning.ComparableVersion) ProjectParseException(meghanada.project.ProjectParseException) GradleConnectionException(org.gradle.tooling.GradleConnectionException) UnsupportedMethodException(org.gradle.tooling.model.UnsupportedMethodException) IOException(java.io.IOException) ProjectParseException(meghanada.project.ProjectParseException) BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) File(java.io.File)

Example 8 with Project

use of meghanada.project.Project in project meghanada-server by mopemope.

the class LocationSearcher method getMethodLocationFromProject.

private Optional<Location> getMethodLocationFromProject(final String methodName, final List<String> arguments, final File file) {
    try {
        final Source declaringClassSrc = getSource(project, file);
        final String path = declaringClassSrc.getFile().getPath();
        return declaringClassSrc.getClassScopes().stream().flatMap(ts -> ts.getScopes().stream()).filter(bs -> {
            if (!methodName.equals(bs.getName())) {
                return false;
            }
            if (!(bs instanceof MethodScope)) {
                return false;
            }
            final MethodScope methodScope = (MethodScope) bs;
            final List<String> parameters = methodScope.getParameters();
            return ClassNameUtils.compareArgumentType(arguments, parameters);
        }).map(MethodScope.class::cast).map(ms -> new Location(path, ms.getBeginLine(), ms.getNameRange().begin.column)).findFirst();
    } catch (ExecutionException e) {
        throw new UncheckedExecutionException(e);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
Also used : DecompilationListener(org.jboss.windup.decompiler.api.DecompilationListener) FunctionUtils.wrapIOConsumer(meghanada.utils.FunctionUtils.wrapIOConsumer) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Map(java.util.Map) ZipFile(java.util.zip.ZipFile) MethodCall(meghanada.analyze.MethodCall) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) FunctionUtils.wrapIO(meghanada.utils.FunctionUtils.wrapIO) GlobalCache(meghanada.cache.GlobalCache) SimpleName(com.github.javaparser.ast.expr.SimpleName) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) StandardOpenOption(java.nio.file.StandardOpenOption) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) MethodScope(meghanada.analyze.MethodScope) ClassNameUtils(meghanada.utils.ClassNameUtils) Optional(java.util.Optional) Project(meghanada.project.Project) Pattern(java.util.regex.Pattern) ProjectDependency(meghanada.project.ProjectDependency) Config(meghanada.config.Config) Parameter(com.github.javaparser.ast.body.Parameter) Position(com.github.javaparser.Position) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Variable(meghanada.analyze.Variable) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ClassScope(meghanada.analyze.ClassScope) OutputStream(java.io.OutputStream) Filter(org.jboss.windup.decompiler.util.Filter) DecompilationResult(org.jboss.windup.decompiler.api.DecompilationResult) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) FileOutputStream(java.io.FileOutputStream) FileUtils.existsFQCN(meghanada.utils.FileUtils.existsFQCN) IOException(java.io.IOException) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) FileUtils(meghanada.utils.FileUtils) EntryMessage(org.apache.logging.log4j.message.EntryMessage) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Paths(java.nio.file.Paths) Source(meghanada.analyze.Source) FernflowerDecompiler(org.jboss.windup.decompiler.fernflower.FernflowerDecompiler) TypeScope(meghanada.analyze.TypeScope) LogManager(org.apache.logging.log4j.LogManager) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) List(java.util.List) ArrayList(java.util.ArrayList) UncheckedIOException(java.io.UncheckedIOException) MethodScope(meghanada.analyze.MethodScope) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Source(meghanada.analyze.Source)

Example 9 with Project

use of meghanada.project.Project in project meghanada-server by mopemope.

the class LocationSearcher method searchDeclarationLocation.

public Optional<Location> searchDeclarationLocation(final File file, final int line, final int column, final String symbol) throws ExecutionException, IOException {
    final Source source = getSource(project, file);
    log.trace("search symbol {}", symbol);
    return this.functions.stream().map(f -> f.apply(source, line, column, symbol)).filter(Optional::isPresent).findFirst().orElse(Optional.empty());
}
Also used : DecompilationListener(org.jboss.windup.decompiler.api.DecompilationListener) FunctionUtils.wrapIOConsumer(meghanada.utils.FunctionUtils.wrapIOConsumer) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Map(java.util.Map) ZipFile(java.util.zip.ZipFile) MethodCall(meghanada.analyze.MethodCall) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) FunctionUtils.wrapIO(meghanada.utils.FunctionUtils.wrapIO) GlobalCache(meghanada.cache.GlobalCache) SimpleName(com.github.javaparser.ast.expr.SimpleName) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) StandardOpenOption(java.nio.file.StandardOpenOption) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) MethodScope(meghanada.analyze.MethodScope) ClassNameUtils(meghanada.utils.ClassNameUtils) Optional(java.util.Optional) Project(meghanada.project.Project) Pattern(java.util.regex.Pattern) ProjectDependency(meghanada.project.ProjectDependency) Config(meghanada.config.Config) Parameter(com.github.javaparser.ast.body.Parameter) Position(com.github.javaparser.Position) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Variable(meghanada.analyze.Variable) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ClassScope(meghanada.analyze.ClassScope) OutputStream(java.io.OutputStream) Filter(org.jboss.windup.decompiler.util.Filter) DecompilationResult(org.jboss.windup.decompiler.api.DecompilationResult) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) FileOutputStream(java.io.FileOutputStream) FileUtils.existsFQCN(meghanada.utils.FileUtils.existsFQCN) IOException(java.io.IOException) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) FileUtils(meghanada.utils.FileUtils) EntryMessage(org.apache.logging.log4j.message.EntryMessage) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Paths(java.nio.file.Paths) Source(meghanada.analyze.Source) FernflowerDecompiler(org.jboss.windup.decompiler.fernflower.FernflowerDecompiler) TypeScope(meghanada.analyze.TypeScope) LogManager(org.apache.logging.log4j.LogManager) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) Optional(java.util.Optional) Source(meghanada.analyze.Source)

Example 10 with Project

use of meghanada.project.Project in project meghanada-server by mopemope.

the class JavaCompletion method completionPackage.

private Collection<? extends CandidateUnit> completionPackage() {
    final GlobalCache globalCache = GlobalCache.getInstance();
    final LoadingCache<File, Source> sourceCache = globalCache.getSourceCache(project);
    return sourceCache.asMap().values().stream().map(source -> ClassIndex.createPackage(source.getPackageName())).collect(Collectors.toSet());
}
Also used : FieldDescriptor(meghanada.reflect.FieldDescriptor) LoadingCache(com.google.common.cache.LoadingCache) AccessSymbol(meghanada.analyze.AccessSymbol) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Variable(meghanada.analyze.Variable) Map(java.util.Map) CandidateUnit(meghanada.reflect.CandidateUnit) MethodCall(meghanada.analyze.MethodCall) ClassScope(meghanada.analyze.ClassScope) GlobalCache(meghanada.cache.GlobalCache) ClassIndex(meghanada.reflect.ClassIndex) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) MemberDescriptor(meghanada.reflect.MemberDescriptor) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) ClassNameUtils(meghanada.utils.ClassNameUtils) Optional(java.util.Optional) Project(meghanada.project.Project) Source(meghanada.analyze.Source) Objects.nonNull(java.util.Objects.nonNull) Comparator(java.util.Comparator) Collections(java.util.Collections) TypeScope(meghanada.analyze.TypeScope) Config(meghanada.config.Config) LogManager(org.apache.logging.log4j.LogManager) GlobalCache(meghanada.cache.GlobalCache) File(java.io.File) Source(meghanada.analyze.Source)

Aggregations

Project (meghanada.project.Project)18 File (java.io.File)13 Config (meghanada.config.Config)10 IOException (java.io.IOException)8 GradleProject (meghanada.project.gradle.GradleProject)8 LogManager (org.apache.logging.log4j.LogManager)8 Logger (org.apache.logging.log4j.Logger)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Map (java.util.Map)7 ExecutionException (java.util.concurrent.ExecutionException)7 GlobalCache (meghanada.cache.GlobalCache)7 ProjectDependency (meghanada.project.ProjectDependency)7 CachedASMReflector (meghanada.reflect.asm.CachedASMReflector)7 InputStream (java.io.InputStream)6 UncheckedIOException (java.io.UncheckedIOException)6 HashMap (java.util.HashMap)6 Optional (java.util.Optional)6 Stream (java.util.stream.Stream)6 Source (meghanada.analyze.Source)6