Search in sources :

Example 11 with CachedASMReflector

use of meghanada.reflect.asm.CachedASMReflector in project meghanada-server by mopemope.

the class LocationSearcher method searchMethodCall.

private Optional<Location> searchMethodCall(final Source source, final int line, final int col, final String symbol) {
    final EntryMessage entryMessage = log.traceEntry("line={} col={} symbol={}", line, col, symbol);
    final Optional<MethodCall> methodCall = source.getMethodCall(line, col, true);
    final Optional<Location> result = methodCall.flatMap(mc -> {
        final String methodName = mc.name;
        final List<String> arguments = mc.getArguments();
        final String declaringClass = mc.declaringClass;
        if (declaringClass == null) {
            return Optional.empty();
        }
        final List<String> searchTargets = new ArrayList<>(2);
        searchTargets.add(declaringClass);
        final CachedASMReflector reflector = CachedASMReflector.getInstance();
        searchTargets.addAll(reflector.getSuperClass(declaringClass));
        return searchTargets.stream().map(targetFqcn -> existsFQCN(project.getAllSourcesWithDependencies(), targetFqcn).flatMap(file -> getMethodLocationFromProject(methodName, arguments, file)).orElseGet(wrapIO(() -> {
            final SearchContext context = new SearchContext(targetFqcn, SearchKind.METHOD);
            context.name = methodName;
            context.arguments = arguments;
            return Optional.ofNullable(searchFromSrcZip(context)).orElseGet(wrapIO(() -> searchFromDependency(context)));
        }))).filter(Objects::nonNull).findFirst();
    });
    log.traceExit(entryMessage);
    return result;
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) ArrayList(java.util.ArrayList) EntryMessage(org.apache.logging.log4j.message.EntryMessage) MethodCall(meghanada.analyze.MethodCall)

Example 12 with CachedASMReflector

use of meghanada.reflect.asm.CachedASMReflector in project meghanada-server by mopemope.

the class TreeAnalyzer method analyzeImports.

private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
    CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();
    long firstLine = 0;
    for (ImportTree imp : cut.getImports()) {
        JCTree.JCImport jcImport = (JCTree.JCImport) imp;
        int startPos = jcImport.getPreferredPosition();
        int endPos = jcImport.getEndPosition(endPosTable);
        Range range = Range.create(src, startPos + 1, endPos);
        firstLine = range.begin.line;
        String importClass = imp.getQualifiedIdentifier().toString();
        String simpleName = ClassNameUtils.getSimpleName(importClass);
        if (imp.isStatic()) {
            // TODO static asterisk
            Tree tree = imp.getQualifiedIdentifier();
            if (tree instanceof JCTree.JCFieldAccess) {
                JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
                com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
                JCTree.JCExpression expression = fieldAccess.getExpression();
                String methodName = name.toString();
                String decClazz = expression.toString();
                src.addStaticImport(methodName, decClazz);
            } else {
                log.warn("Not impl");
            }
        } else {
            if (simpleName.equals("*")) {
                // wild
                for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
                    src.addImport(s);
                }
            } else {
                src.addImport(importClass);
            }
        }
    }
    src.setClassStartLine(firstLine);
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) JCTree(com.sun.tools.javac.tree.JCTree) VariableTree(com.sun.source.tree.VariableTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) ImportTree(com.sun.source.tree.ImportTree)

Example 13 with CachedASMReflector

use of meghanada.reflect.asm.CachedASMReflector in project meghanada-server by mopemope.

the class Source method searchMissingImport.

private Map<String, List<String>> searchMissingImport(boolean addAll) {
    final CachedASMReflector reflector = CachedASMReflector.getInstance();
    // search missing imports
    final Map<String, List<String>> ask = new HashMap<>(4);
    log.debug("unknown class size:{} classes:{}", this.unknown.size(), this.unknown);
    final Map<String, String> importedClassMap = this.getImportedClassMap();
    for (final String clazzName : this.unknown) {
        String searchWord = ClassNameUtils.removeTypeAndArray(clazzName);
        final int i = searchWord.indexOf('.');
        if (i > 0) {
            searchWord = searchWord.substring(0, i);
        }
        if (searchWord.isEmpty()) {
            continue;
        }
        if (importedClassMap.containsKey(searchWord)) {
            continue;
        }
        log.debug("search unknown class : '{}' ...", searchWord);
        final Collection<? extends CandidateUnit> findUnits = reflector.searchClasses(searchWord, false, false);
        log.debug("find candidate units : {}", findUnits);
        if (findUnits.size() == 0) {
            continue;
        }
        if (findUnits.size() == 1) {
            final CandidateUnit[] candidateUnits = findUnits.toArray(new CandidateUnit[1]);
            final String declaration = candidateUnits[0].getDeclaration();
            final String pa = ClassNameUtils.getPackage(declaration);
            if (pa.equals("java.lang")) {
                continue;
            }
            if (nonNull(this.packageName) && pa.equals(this.packageName)) {
                // remove same package
                continue;
            }
            if (addAll) {
                ask.put(clazzName, Collections.singletonList(candidateUnits[0].getDeclaration()));
            }
        } else {
            final List<String> imports = findUnits.stream().map(CandidateUnit::getDeclaration).collect(Collectors.toList());
            if (!imports.isEmpty()) {
                ask.put(clazzName, imports);
            }
        }
    }
    return ask;
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) CandidateUnit(meghanada.reflect.CandidateUnit)

Example 14 with CachedASMReflector

use of meghanada.reflect.asm.CachedASMReflector in project meghanada-server by mopemope.

the class Source method addImportIfAbsent.

public boolean addImportIfAbsent(final String fqcn) {
    if (this.importClasses.contains(fqcn)) {
        return false;
    }
    for (final ClassScope classScope : this.classScopes) {
        if (Source.includeInnerClass(classScope, fqcn)) {
            return false;
        }
    }
    final CachedASMReflector reflector = CachedASMReflector.getInstance();
    if (fqcn.startsWith(this.packageName)) {
        final Map<String, String> packageClasses = reflector.getPackageClasses(this.packageName);
        final boolean find = packageClasses.values().stream().filter(s -> s.equals(fqcn)).map(s -> true).findFirst().orElseGet(() -> {
            // TODO search inner class
            return false;
        });
        if (find) {
            return false;
        }
    }
    this.importClasses.add(fqcn);
    return true;
}
Also used : HashMap(java.util.HashMap) Deque(java.util.Deque) LineMap(com.sun.source.tree.LineMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) Charset(java.nio.charset.Charset) Map(java.util.Map) CandidateUnit(meghanada.reflect.CandidateUnit) Objects.isNull(java.util.Objects.isNull) Nonnull(javax.annotation.Nonnull) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) GlobalCache(meghanada.cache.GlobalCache) StoreTransaction(jetbrains.exodus.entitystore.StoreTransaction) ClassIndex(meghanada.reflect.ClassIndex) Collection(java.util.Collection) MoreObjects(com.google.common.base.MoreObjects) Set(java.util.Set) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) EntryMessage(org.apache.logging.log4j.message.EntryMessage) File(java.io.File) Entity(jetbrains.exodus.entitystore.Entity) Serializable(java.io.Serializable) UncheckedIOException(java.io.UncheckedIOException) MemberDescriptor(meghanada.reflect.MemberDescriptor) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClassNameUtils(meghanada.utils.ClassNameUtils) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Objects.nonNull(java.util.Objects.nonNull) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) EntityId(jetbrains.exodus.entitystore.EntityId) Storable(meghanada.store.Storable) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector)

Example 15 with CachedASMReflector

use of meghanada.reflect.asm.CachedASMReflector in project meghanada-server by mopemope.

the class JavaCompletion method completionImport.

private static List<ClassIndex> completionImport(final String searchWord) {
    final Config config = Config.load();
    final boolean useFuzzySearch = config.useClassFuzzySearch();
    final int idx = searchWord.lastIndexOf(':');
    final Stream<ClassIndex> stream;
    final CachedASMReflector reflector = CachedASMReflector.getInstance();
    if (idx > 0) {
        final String classPrefix = searchWord.substring(idx + 1, searchWord.length());
        if (useFuzzySearch) {
            stream = reflector.fuzzySearchClassesStream(classPrefix.toLowerCase(), false);
        } else {
            stream = reflector.searchClassesStream(classPrefix.toLowerCase(), true, false);
        }
        return stream.map(cl -> {
            cl.setMemberType(CandidateUnit.MemberType.IMPORT);
            return cl;
        }).sorted(comparing(classPrefix)).collect(Collectors.toList());
    }
    return Collections.emptyList();
}
Also used : ClassIndex(meghanada.reflect.ClassIndex) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) Config(meghanada.config.Config)

Aggregations

CachedASMReflector (meghanada.reflect.asm.CachedASMReflector)29 ArrayList (java.util.ArrayList)11 ClassIndex (meghanada.reflect.ClassIndex)9 EntryMessage (org.apache.logging.log4j.message.EntryMessage)9 File (java.io.File)8 HashSet (java.util.HashSet)8 CandidateUnit (meghanada.reflect.CandidateUnit)7 List (java.util.List)6 Map (java.util.Map)6 Optional (java.util.Optional)6 IOException (java.io.IOException)5 ClassScope (meghanada.analyze.ClassScope)5 Config (meghanada.config.Config)5 MemberDescriptor (meghanada.reflect.MemberDescriptor)5 LogManager (org.apache.logging.log4j.LogManager)5 Logger (org.apache.logging.log4j.Logger)5 Stopwatch (com.google.common.base.Stopwatch)4 UncheckedIOException (java.io.UncheckedIOException)4 Collection (java.util.Collection)4 Collections (java.util.Collections)4