Support for Cross-File (Multi-File) Analysis in SonarQube Custom Rules (Java)

Hi, I’m new to SonarQube and currently using the community edition. I have a question regarding rule creation and multi-file analysis, specifically for Java projects.

Is it possible in SonarQube to create a custom rule that analyzes across multiple Java files? For example, if a method in one file triggers or interacts with code in 5–10 other files, can a custom rule be written to evaluate that entire context, or are rules limited to analyzing each file independently?

If cross-file analysis is supported, could someone point me to documentation or an example for Java? And if there’s already a built-in rule that performs this kind of analysis, I’d appreciate it if you could share which one.

Thanks in advance for your help!

Hi @sidhu ,

The custom rule api does not support multi-file analysis. You should also be aware that the Java analyzer performs multiple executions during a single project analysis. One per Maven/Gradle sub-module. There are two types of multi-file analysis: one at the module level and one at the project level.

In the Java analyzer, there are rules called at the end of each module because they implement org.sonar.plugins.java.api.internal.EndOfAnalysis, like ExcessiveContentRequestCheck, but it’s a complex mechanism to support incremental analysis. The rules need to support scanWithoutParsing(InputFileScannerContext context) for unmodified files. So it is not easy to expose this feature in the custom rule api, which is why we do not provide it.

It is also possible to create a class that is called at the end of the project analysis. Like this ProjectEndOfAnalysisSensor, added by the plugin here. It is not executed for each module, but only at the end, because of implements ProjectSensor and @Phase(name = Phase.Name.POST).

And there are objects in the context with @ScannerSide @SonarLintSide @ExtensionPoint, like Telemetry, which could be injected into different constructors to share the state during the analysis. But, this is too complex to put in place in the context of custom rules.