[Custom Language Plugin]How to find the duplicate element

已回答

Hello, I'm develop a custom language plugin. When i define the annotator, i need compare the current element with other the same type element in the whole project. My solution is searching all the same type element and comparing their name when annotate any element. It need much time. can any api help me?

0
public static @NotNull List<BjscClass> findClasses(Project project, String javaPackageDesc, String className) {
List<BjscClass> result = new ArrayList<>();
Collection<VirtualFile> virtualFiles =
FileTypeIndex.getFiles(BjscFileType.INSTANCE, GlobalSearchScope.allScope(project));

for (VirtualFile virtualFile : virtualFiles) {
BjscFile bjscFile = (BjscFile)PsiManager.getInstance(project).findFile(virtualFile);
if (Objects.isNull(bjscFile)) {
continue;
}
List<BjscJavaPackageDesc> javaPackageDescList =
new ArrayList<>(PsiTreeUtil.findChildrenOfType(bjscFile, BjscJavaPackageDesc.class));
if (CollectionUtils.isEmpty(javaPackageDescList)) {
continue;
}
String currentJavaPackageDesc = javaPackageDescList.get(0).getText();
if (!StringUtil.equals(currentJavaPackageDesc, javaPackageDesc)) {
continue;
}
List<BjscClass> bjscClassList = new ArrayList<>(PsiTreeUtil.findChildrenOfType(bjscFile, BjscClass.class));
List<BjscClass> subBjscClassList = bjscClassList.stream()
.filter(item -> StringUtil.equals(item.getClassName(), className)).collect(Collectors.toList());
result.addAll(subBjscClassList);
}
return result;
}

 

if a class's javaPackageDesc and className is same with another class's, then them are duplicate. My idea is use a static variable to store all the classes in the project to avoid to query all the classes everytime. Is this possible?


if possible, when the project changed, how can i update the static variable promptly?

0

Hi,

I'm not sure I understand your use case. If you want to highlight an element if there is a "duplicate" element in the project, then you should find it in the annotator in a regular way and cache the result. See https://plugins.jetbrains.com/docs/intellij/psi-performance.html#cache-results-of-heavy-computations.

You can also use indexes to speed up finding duplicates, if possible. See all the sections under https://plugins.jetbrains.com/docs/intellij/indexing-and-psi-stubs.html.

0

Hi Karol, thank you for your advice. The stubIndex is useful

0

If you find a duplicate element, you can compare them by element.getContainingFile().getVirtualFile().getPath(). Package and class names which are strings, are not enough.

0

Thanks, it seems that i use the wrong method. StubIndex.getElements() is useful !

 

0

请先登录再写评论。