Search in sources :

Example 1 with Variable

use of meghanada.analyze.Variable in project meghanada-server by mopemope.

the class LocationSearcher method searchLocalVariable.

private Optional<Location> searchLocalVariable(final Source source, final int line, final int col, final String symbol) {
    final EntryMessage entryMessage = log.traceEntry("line={} col={} symbol={}", line, col, symbol);
    final Map<String, Variable> variableMap = source.getVariableMap(line);
    log.trace("variables={}", variableMap);
    final Optional<Variable> variable = Optional.ofNullable(variableMap.get(symbol));
    final Optional<Location> location = variable.map(var -> {
        if (var.isDecl()) {
            final Location loc = new Location(source.getFile().getPath(), var.range.begin.line, var.range.begin.column);
            return Optional.of(loc);
        } else {
            final String fqcn = var.fqcn;
            final Location loc = getFQCNLocation(fqcn);
            return Optional.ofNullable(loc);
        }
    }).orElseGet(() -> {
        // isField
        final Optional<TypeScope> ts = source.getTypeScope(line);
        if (!ts.isPresent()) {
            return Optional.empty();
        }
        return ts.get().getField(symbol).map(fieldSymbol -> new Location(source.getFile().getPath(), fieldSymbol.range.begin.line, fieldSymbol.range.begin.column));
    });
    log.traceExit(entryMessage);
    return location;
}
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) Variable(meghanada.analyze.Variable) TypeScope(meghanada.analyze.TypeScope) EntryMessage(org.apache.logging.log4j.message.EntryMessage)

Example 2 with Variable

use of meghanada.analyze.Variable 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 3 with Variable

use of meghanada.analyze.Variable 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 4 with Variable

use of meghanada.analyze.Variable in project meghanada-server by mopemope.

the class ReferenceSearcher method searchMemberCondition.

private static Optional<SearchCondition> searchMemberCondition(Source source, int line, int col, String symbol) {
    EntryMessage msg = log.traceEntry("line={} col={} symbol={}", line, col, symbol);
    for (ClassScope classScope : source.getClassScopes()) {
        for (Variable variable : classScope.getVariables()) {
            if (variable.isField) {
                Position pos = variable.range.begin;
                String name = variable.name;
                if (pos.line == line && name.equals(symbol)) {
                    String clazz = classScope.getFQCN();
                    SearchCondition condition = new SearchCondition(clazz, name, SearchCondition.Type.FIELD);
                    return Optional.of(condition);
                }
            }
        }
        for (BlockScope blockScope : classScope.getScopes()) {
            if (blockScope instanceof MethodScope) {
                MethodScope methodScope = ((MethodScope) blockScope);
                Position pos = methodScope.getNameRange().begin;
                String name = methodScope.getName();
                if (pos.line == line && name.equals(symbol)) {
                    String clazz = classScope.getFQCN();
                    SearchCondition condition = new SearchCondition(clazz, name, SearchCondition.Type.METHOD, methodScope.getParameters());
                    return Optional.of(condition);
                }
            }
        }
    }
    log.traceExit(msg);
    return Optional.empty();
}
Also used : Variable(meghanada.analyze.Variable) Position(meghanada.analyze.Position) BlockScope(meghanada.analyze.BlockScope) MethodScope(meghanada.analyze.MethodScope) EntryMessage(org.apache.logging.log4j.message.EntryMessage) ClassScope(meghanada.analyze.ClassScope)

Example 5 with Variable

use of meghanada.analyze.Variable in project meghanada-server by mopemope.

the class DeclarationSearcher method searchLocalVariable.

private static Optional<Declaration> searchLocalVariable(final Source source, final Integer line, final Integer col, final String symbol) {
    final EntryMessage entryMessage = log.traceEntry("line={} col={} symbol={}", line, col, symbol);
    final Optional<Variable> variable = source.getVariable(line, col);
    final Optional<Declaration> result = variable.map(var -> {
        final Declaration declaration = new Declaration(symbol, var.fqcn, Declaration.Type.VAR, var.argumentIndex);
        return Optional.of(declaration);
    }).orElseGet(() -> searchFieldVar(source, line, symbol));
    log.traceExit(entryMessage);
    return result;
}
Also used : FileUtils.getSource(meghanada.utils.FileUtils.getSource) ClassIndex(meghanada.reflect.ClassIndex) Set(java.util.Set) IOException(java.io.IOException) CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) EntryMessage(org.apache.logging.log4j.message.EntryMessage) File(java.io.File) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ExecutionException(java.util.concurrent.ExecutionException) Variable(meghanada.analyze.Variable) MemberDescriptor(meghanada.reflect.MemberDescriptor) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClassNameUtils(meghanada.utils.ClassNameUtils) Optional(java.util.Optional) Project(meghanada.project.Project) MethodCall(meghanada.analyze.MethodCall) ClassScope(meghanada.analyze.ClassScope) Source(meghanada.analyze.Source) LogManager(org.apache.logging.log4j.LogManager) Joiner(com.google.common.base.Joiner) Variable(meghanada.analyze.Variable) EntryMessage(org.apache.logging.log4j.message.EntryMessage)

Aggregations

Variable (meghanada.analyze.Variable)6 ClassScope (meghanada.analyze.ClassScope)5 CachedASMReflector (meghanada.reflect.asm.CachedASMReflector)5 ArrayList (java.util.ArrayList)4 Optional (java.util.Optional)4 MethodCall (meghanada.analyze.MethodCall)4 EntryMessage (org.apache.logging.log4j.message.EntryMessage)4 File (java.io.File)3 IOException (java.io.IOException)3 List (java.util.List)3 Map (java.util.Map)3 JavaParser (com.github.javaparser.JavaParser)2 Position (com.github.javaparser.Position)2 CompilationUnit (com.github.javaparser.ast.CompilationUnit)2 BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)2 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)2 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)2 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)2 Parameter (com.github.javaparser.ast.body.Parameter)2 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)2