public static PsiExpression[] findVariableOccurrences(final PsiElement[] scopeElements, final PsiVariable variable) { final ArrayList<PsiExpression> result = new ArrayList<PsiExpression>(); for (final PsiElement element : scopeElements) { element.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(final PsiReferenceExpression expression) { super.visitReferenceExpression(expression); if (!expression.isQualified() && expression.isReferenceTo(variable)) { result.add(expression); } } }); } return result.toArray(new PsiExpression[result.size()]); }
private static List<PsiClass> getInnerClasses(PsiElement psiElement, final CharSequence fileBuffer) { final Ref<ArrayList<PsiClass>> ourList = new Ref<ArrayList<PsiClass>>(); ourList.set(null); if(psiElement != null && mayContainClassesInside(psiElement, fileBuffer)) { psiElement.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitClass(PsiClass aClass) { if(ourList.isNull()) { ourList.set(new ArrayList<PsiClass>()); } ourList.get().add(aClass); } @Override public void visitTypeParameter(PsiTypeParameter classParameter) { // just skip (because type parameter is class - bad!) } }); } return ourList.get(); }
@Override protected Response handle(Request request) { Project project = findProject(request.file); if (project == null) { throw new RuntimeException("Cannot find the target project"); } Application application = ApplicationManager.getApplication(); Response response = new Response(); application.runReadAction( () -> { PsiFile psiFile = PsiFileFactory.getInstance(project) .createFileFromText(JavaLanguage.INSTANCE, request.text); if (!(psiFile instanceof PsiJavaFile)) { throw new RuntimeException("Cannot parse as Java file"); } PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile; Set<String> processed = new HashSet<>(); for (PsiClass psiClass : psiJavaFile.getClasses()) { psiClass.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { try { if (reference.getQualifier() != null) { return; } String name = reference.getReferenceName(); if (processed.contains(name)) { return; } processed.add(name); Set<String> candidates = new HashSet<>(); for (PsiClass t : new ImportClassFix(reference).getClassesToImport()) { candidates.add(String.format("import %s;", t.getQualifiedName())); } if (!candidates.isEmpty()) { response.choices.add(candidates.stream().sorted().collect(toList())); } } finally { super.visitReferenceElement(reference); } } }); } }); return response; }