Search in sources :

Example 1 with CandidateUnit

use of meghanada.reflect.CandidateUnit 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 2 with CandidateUnit

use of meghanada.reflect.CandidateUnit 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)

Example 3 with CandidateUnit

use of meghanada.reflect.CandidateUnit in project meghanada-server by mopemope.

the class JavaCompletion method completionSymbols.

private static Collection<? extends CandidateUnit> completionSymbols(Source source, int line, String prefix) {
    Set<CandidateUnit> result = new HashSet<>(32);
    // prefix search
    log.debug("Search variables prefix:{} line:{}", prefix, line);
    Optional<TypeScope> typeScope = source.getTypeScope(line);
    if (!typeScope.isPresent()) {
        return result;
    }
    String fqcn = typeScope.get().getFQCN();
    // add this member
    for (MemberDescriptor c : JavaCompletion.reflectSelf(fqcn, true, prefix)) {
        if (c.getName().startsWith(prefix)) {
            result.add(c);
        }
    }
    if (fqcn.contains(ClassNameUtils.INNER_MARK)) {
        // add parent
        String parentClass = fqcn;
        while (true) {
            int i = parentClass.lastIndexOf('$');
            if (i < 0) {
                break;
            }
            parentClass = parentClass.substring(0, i);
            for (MemberDescriptor c : JavaCompletion.reflectSelf(parentClass, true, prefix)) {
                if (c.getName().startsWith(prefix)) {
                    result.add(c);
                }
            }
        }
    }
    log.debug("self fqcn:{}", fqcn);
    Map<String, Variable> symbols = source.getDeclaratorMap(line);
    log.debug("search variables size:{} result:{}", symbols.size(), symbols);
    for (Map.Entry<String, Variable> e : symbols.entrySet()) {
        String k = e.getKey();
        Variable v = e.getValue();
        log.debug("check variable name:{}", k);
        if (k.startsWith(prefix)) {
            log.debug("match variable name:{}", k);
            if (!v.isField) {
                result.add(v.toCandidateUnit());
            }
        }
    }
    // import
    for (Map.Entry<String, String> e : source.getImportedClassMap().entrySet()) {
        String k = e.getKey();
        String v = e.getValue();
        if (k.startsWith(prefix)) {
            result.add(ClassIndex.createClass(v));
        }
    }
    // static import
    for (Map.Entry<String, String> e : source.staticImportClass.entrySet()) {
        String methodName = e.getKey();
        String clazz = e.getValue();
        for (MemberDescriptor md : JavaCompletion.reflectWithFQCN(clazz, methodName)) {
            if (md.getName().equals(methodName)) {
                result.add(md);
            }
        }
    }
    // Add class
    if (Character.isUpperCase(prefix.charAt(0))) {
        // completion
        CachedASMReflector reflector = CachedASMReflector.getInstance();
        boolean fuzzySearch = Config.load().useClassFuzzySearch();
        if (fuzzySearch) {
            result.addAll(reflector.fuzzySearchClasses(prefix.toLowerCase()));
        } else {
            result.addAll(reflector.searchClasses(prefix.toLowerCase()));
        }
    }
    List<CandidateUnit> list = new ArrayList<>(result);
    list.sort(comparing(source, prefix));
    return list;
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) Variable(meghanada.analyze.Variable) MemberDescriptor(meghanada.reflect.MemberDescriptor) ArrayList(java.util.ArrayList) TypeScope(meghanada.analyze.TypeScope) CandidateUnit(meghanada.reflect.CandidateUnit) Map(java.util.Map) HashSet(java.util.HashSet)

Example 4 with CandidateUnit

use of meghanada.reflect.CandidateUnit in project meghanada-server by mopemope.

the class JavaCompletion method completionFieldsOrMethods.

private static Collection<? extends CandidateUnit> completionFieldsOrMethods(final Source source, final int line, final String var, final String target) {
    // completionAt methods or fields
    if (var.equals("this")) {
        return JavaCompletion.completionThis(source, line, target);
    }
    if (var.equals("super")) {
        return JavaCompletion.completionSuper(source, line, target);
    }
    log.debug("search '{}' field or method", var);
    String ownPackage = source.getPackageName();
    final Set<CandidateUnit> res = new HashSet<>(32);
    {
        // completion static method
        String fqcn = source.getImportedClassFQCN(var, null);
        if (nonNull(fqcn)) {
            if (!fqcn.contains(".") && !ownPackage.isEmpty()) {
                fqcn = ownPackage + '.' + fqcn;
            }
            final Collection<? extends CandidateUnit> result = JavaCompletion.reflect(ownPackage, fqcn, true, false, target);
            res.addAll(result);
            // add inner class
            final Collection<? extends CandidateUnit> inners = CachedASMReflector.getInstance().searchInnerClasses(fqcn);
            res.addAll(inners);
            if (!res.isEmpty()) {
                return res;
            }
        }
    }
    {
        final Map<String, Variable> symbols = source.getDeclaratorMap(line);
        final Variable variable = symbols.get(var);
        if (nonNull(variable)) {
            // get data from reflector
            String fqcn = variable.fqcn;
            if (!fqcn.contains(".")) {
                fqcn = ownPackage + '.' + fqcn;
            }
            final Collection<? extends CandidateUnit> reflect = JavaCompletion.reflect(ownPackage, fqcn, target);
            res.addAll(reflect);
        }
    }
    {
        for (final ClassScope cs : source.getClassScopes()) {
            final String fqcn = cs.getFQCN();
            final Optional<MemberDescriptor> fieldResult = JavaCompletion.reflectSelf(fqcn, true, target).stream().filter(c -> c instanceof FieldDescriptor && c.getName().equals(var)).findFirst();
            if (fieldResult.isPresent()) {
                final MemberDescriptor memberDescriptor = fieldResult.orElse(null);
                final String returnType = memberDescriptor.getRawReturnType();
                final Collection<? extends CandidateUnit> reflect = reflect(ownPackage, returnType, target);
                res.addAll(reflect);
            }
        }
    }
    {
        // java.lang
        final String fqcn = "java.lang." + var;
        final Collection<? extends CandidateUnit> result = JavaCompletion.reflect(ownPackage, fqcn, true, false, target);
        res.addAll(result);
    }
    {
        String fqcn = var;
        if (!ownPackage.isEmpty()) {
            fqcn = ownPackage + '.' + var;
        }
        final Collection<? extends CandidateUnit> reflectResults = JavaCompletion.reflect(ownPackage, fqcn, true, false, target);
        res.addAll(reflectResults);
        final CachedASMReflector reflector = CachedASMReflector.getInstance();
        if (reflector.containsFQCN(fqcn)) {
            final Collection<? extends CandidateUnit> inners = reflector.searchInnerClasses(fqcn);
            res.addAll(inners);
        }
    }
    if (line > 0 && res.isEmpty()) {
        List<MethodCall> calls = source.getMethodCall(line - 1);
        long lastCol = 0;
        String lastFQCN = null;
        for (MethodCall call : calls) {
            long col = call.nameRange.begin.column;
            String name = ClassNameUtils.getSimpleName(call.name);
            if (name.equals(var) && col > lastCol) {
                lastFQCN = call.returnType;
                lastCol = col;
            }
        }
        if (nonNull(lastFQCN)) {
            res.addAll(reflectWithFQCN(lastFQCN, ""));
        }
    }
    return res;
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) Variable(meghanada.analyze.Variable) Optional(java.util.Optional) MemberDescriptor(meghanada.reflect.MemberDescriptor) MethodCall(meghanada.analyze.MethodCall) ClassScope(meghanada.analyze.ClassScope) FieldDescriptor(meghanada.reflect.FieldDescriptor) Collection(java.util.Collection) CandidateUnit(meghanada.reflect.CandidateUnit) Map(java.util.Map) HashSet(java.util.HashSet)

Example 5 with CandidateUnit

use of meghanada.reflect.CandidateUnit in project meghanada-server by mopemope.

the class JavaCompletionTest method testCompletion08.

@Test
public void testCompletion08() throws Exception {
    JavaCompletion completion = getCompletion();
    File file = new File("./src/main/java/meghanada/analyze/JavaAnalyzer.java").getCanonicalFile();
    assertTrue(file.exists());
    final Collection<? extends CandidateUnit> units = timeIt(() -> completion.completionAt(file, 79, 35, "*method:java.util.Iterator<capture of ? extends com.sun.source.tree.CompilationUnitTree>#"));
    // units.forEach(a -> System.out.println(a.getDisplayDeclaration()));
    assertEquals(13, units.size());
    for (CandidateUnit unit : units) {
        if (unit.getName().equals("next")) {
            final String returnType = unit.getReturnType();
            assertEquals("capture of ? extends com.sun.source.tree.CompilationUnitTree", returnType);
        }
    }
}
Also used : CandidateUnit(meghanada.reflect.CandidateUnit) File(java.io.File) Test(org.junit.Test)

Aggregations

CandidateUnit (meghanada.reflect.CandidateUnit)5 CachedASMReflector (meghanada.reflect.asm.CachedASMReflector)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Variable (meghanada.analyze.Variable)3 MemberDescriptor (meghanada.reflect.MemberDescriptor)3 File (java.io.File)2 Collection (java.util.Collection)2 List (java.util.List)2 Optional (java.util.Optional)2 ClassScope (meghanada.analyze.ClassScope)2 MethodCall (meghanada.analyze.MethodCall)2 TypeScope (meghanada.analyze.TypeScope)2 FieldDescriptor (meghanada.reflect.FieldDescriptor)2 LoadingCache (com.google.common.cache.LoadingCache)1 IOException (java.io.IOException)1 Collections (java.util.Collections)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1