Unused imports problem with a simple variation of Java

Answered

I've been successful in developing a plugin that provides custom syntax highlighting for a very simple variation of Java. I could really use some suggestions on how to pursue the next step.

An example of my variation is shown below in which any Java statements between a leading '/*--' and a trailing '--*/' are treated as executable code. The problem is that both the import statements are analyzed as unused and are highlighted accordingly. For the first, the analysis is correct, but for the second it is not. How can I ensure the second import statement is not highlighted as being unused?

import java.util.ArrayList;
import java.util.Arrays;

public class MyClass
{
public static void main(String[] args)
{
String myString = "";
/*--
myString = Arrays.asList("Hello world!").get(0);
--*/
System.out.println(myString);
}
}

Any help would be greatly appreciated.

0
4 comments

Unused imports are detected with `UnusedImportInspection` (`globalInspection` Extension Point). This inspection invokes logic from `ImportsAreUsedVisitor` class and produces "problems".
You can try to extend and override this inspection `UnusedImportInspection` or suppress this highlighting via `com.intellij.codeInspection.InspectionSuppressor#isSuppressedFor`

 

0

Thank you for the response.

I have tried many approaches, but have been unsuccessful extending and overriding the  `UnusedImportInspection`; I can create a custom extension that extends `UnusedImportInspection`, but I have been unsuccessful in overriding the original or removing the original and replacing my custom one. A previous post makes me concerned.

Also, although I can set breakpoints on the checkFile() method of local inspections and see it execute, I cannot seem to set a breakpoint on the checkFile() method of any global inspections, including the `UnusedImportInspection`. Is that to be expected?

0

I've played with that a bit - and you're right, it will not work.

Since 2019.3 (193) there was new Extension Point introduced: 

<highlightInfoPostFilter implementation="MyHighlightInfoPostFilter" />

It allows checking HighlightInfos that are reported for the current file:

public class MyHighlightInfoPostFilter implements HighlightInfoPostFilter {
@Override
public boolean accept(@NotNull HighlightInfo highlightInfo) {
if (highlightInfo.type.getAttributesKey().equals(CodeInsightColors.NOT_USED_ELEMENT_ATTRIBUTES)) {
return false;
}
return true;
}
}

Also, you should check the

highlightInfo.psiElement

if it matches certain conditions (class is used inside comments).

0

That's it Jakub! 

I was just exploring that section of code, but I didn't notice there was a new Extension Point. 

Thank you.

0

Please sign in to leave a comment.