-
Notifications
You must be signed in to change notification settings - Fork 720
SONARJAVA-6096 Group import declarations by specificity #5457
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
31a4022
aa144b5
f7bccda
7927212
4c22668
44d8fea
8d5b335
989c74f
7a18835
5875311
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "ruleKey": "S8445", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 0, | ||
| "falsePositives": 0 | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package checks; | ||
|
|
||
| // Basic violation: package import after single-type import | ||
| import java.util.List; // Compliant | ||
| import java.io.*; // Noncompliant {{Reorder this on-demand package import to come before single-type imports.}} | ||
| // ^^^^^^^^^ | ||
| import java.util.Map; // Compliant | ||
|
|
||
| // Static import violations | ||
| import static java.lang.Math.PI; // Compliant | ||
| import static java.util.Collections.*; // Noncompliant {{Reorder this static on-demand package import to come before static single-type imports.}} | ||
| // ^^^^^^^^^^^^^^^^^^^^^^^ | ||
| // Module import violation - comes after static imports | ||
| import module java.base; // Noncompliant {{Reorder this module import to come before static on-demand package imports.}} | ||
|
|
||
| // These are compliant since they come after module import (which resets the ordering) | ||
| import java.sql.*; // Compliant | ||
tomasz-tylenda-sonarsource marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import java.time.Instant; // Compliant | ||
| import static java.lang.System.out; // Compliant | ||
|
|
||
| class ImportDeclarationOrderCheckSample { | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package checks; | ||
|
|
||
| // All imports in correct order - no violations expected | ||
|
|
||
| // Module imports | ||
| import module java.base; | ||
asya-vorobeva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Package imports (on-demand) | ||
| import java.io.*; | ||
| import java.sql.*; | ||
|
|
||
| // Single-type imports | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.time.Instant; | ||
|
|
||
| // Static package imports (on-demand) | ||
| import static java.util.Collections.*; | ||
|
|
||
| // Static single-type imports | ||
| import static java.lang.Math.PI; | ||
| import static java.lang.System.out; | ||
|
|
||
|
|
||
| class ImportDeclarationOrderCheckSampleNoIssuesSample { | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) 2012-2025 SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.JavaVersion; | ||
| import org.sonar.plugins.java.api.JavaVersionAwareVisitor; | ||
| import org.sonar.plugins.java.api.tree.CompilationUnitTree; | ||
| import org.sonar.plugins.java.api.tree.ImportTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
|
|
||
| @Rule(key = "S8445") | ||
| public class ImportDeclarationOrderCheck extends IssuableSubscriptionVisitor implements JavaVersionAwareVisitor { | ||
|
|
||
| @Override | ||
| public boolean isCompatibleWithJavaVersion(JavaVersion version) { | ||
asya-vorobeva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return version.isJava25Compatible(); | ||
| } | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return Collections.singletonList(Tree.Kind.COMPILATION_UNIT); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| CompilationUnitTree compilationUnit = (CompilationUnitTree) tree; | ||
|
|
||
| List<ImportTree> imports = new ArrayList<>(); | ||
| // Collect all import statements | ||
| compilationUnit.imports() | ||
| .stream() | ||
| .filter(importTree -> importTree.is(Tree.Kind.IMPORT)) | ||
| .map(ImportTree.class::cast) | ||
| .forEach(imports::add); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. using
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's really preferred when it's publicly accessible / can be potentially modified by external modules. In the case when it's private access within one class, I don't think it's important. |
||
|
|
||
| analyzeImportOrder(imports); | ||
| } | ||
|
|
||
| private void analyzeImportOrder(List<ImportTree> imports) { | ||
| if (imports.size() <= 1) { | ||
| return; | ||
| } | ||
|
|
||
| ImportType previousType = ImportType.SENTINEL_IMPORT; | ||
| for (ImportTree importTree : imports) { | ||
| ImportType currentType = classifyImport(importTree); | ||
|
|
||
| if (currentType.ordinal() < previousType.ordinal()) { | ||
| String message = buildMessage(currentType, previousType); | ||
| reportIssue(importTree.qualifiedIdentifier(), message); | ||
| } | ||
|
|
||
| previousType = currentType; | ||
| } | ||
| } | ||
|
|
||
| private static String buildMessage(ImportType currentType, ImportType previousType) { | ||
| return String.format("Reorder this %s import to come before %s imports.", | ||
| currentType.getDescription(), | ||
| previousType.getDescription()); | ||
| } | ||
|
|
||
| private static ImportType classifyImport(ImportTree importTree) { | ||
| boolean isWildcard = isWildcardImport(importTree); | ||
|
|
||
| if (importTree.isModule()) { | ||
| return ImportType.MODULE_IMPORT; | ||
| } | ||
|
|
||
| if (importTree.isStatic()) { | ||
| return isWildcard ? ImportType.STATIC_PACKAGE_IMPORT : ImportType.STATIC_SINGLE_TYPE_IMPORT; | ||
| } | ||
|
|
||
| return isWildcard ? ImportType.PACKAGE_IMPORT : ImportType.SINGLE_TYPE_IMPORT; | ||
| } | ||
|
|
||
| private static boolean isWildcardImport(ImportTree importTree) { | ||
| return "*".equals(importTree.qualifiedIdentifier().lastToken().text()); | ||
| } | ||
|
|
||
| enum ImportType { | ||
| SENTINEL_IMPORT("sentinel"), | ||
| MODULE_IMPORT("module"), | ||
| PACKAGE_IMPORT("on-demand package"), | ||
| SINGLE_TYPE_IMPORT("single-type"), | ||
| STATIC_PACKAGE_IMPORT("static on-demand package"), | ||
| STATIC_SINGLE_TYPE_IMPORT("static single-type"); | ||
|
|
||
| private final String description; | ||
|
|
||
| ImportType(String description) { | ||
| this.description = description; | ||
| } | ||
|
|
||
| public String getDescription() { | ||
| return description; | ||
| } | ||
| } | ||
| } | ||
asya-vorobeva marked this conversation as resolved.
Show resolved
Hide resolved
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) 2012-2025 SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class ImportDeclarationOrderCheckTest { | ||
|
|
||
| @Test | ||
| void basic_import_ordering() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSample.java")) | ||
| .withCheck(new ImportDeclarationOrderCheck()) | ||
| .withJavaVersion(25) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void no_issue_on_java_24() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSample.java")) | ||
| .withCheck(new ImportDeclarationOrderCheck()) | ||
| .withJavaVersion(24) | ||
| .verifyNoIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("The same imports but correctly ordered") | ||
| void correctly_ordered_imports() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSampleNoIssuesSample.java")) | ||
| .withCheck(new ImportDeclarationOrderCheck()) | ||
| .withJavaVersion(25) | ||
| .verifyNoIssues(); | ||
| } | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| <p>This rule raises an issue when import declarations are not organized into distinct groups based on their kind and specificity level.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p>Import declarations should be organized into distinct groups based on their kind to improve readability and make shadowing behavior explicit. The | ||
| grouping order should reflect specificity levels: module imports first (least specific), followed by on-demand package imports (intermediate | ||
| specificity), single-type imports (most specific), then static on-demand imports, and finally single-static imports.</p> | ||
| <p>When imports are mixed or ordered arbitrarily, it becomes harder to understand which declarations might shadow others. Java’s import shadowing | ||
| rules mean that more specific imports can override less specific ones, so organizing imports by specificity makes these relationships clearer and | ||
| improves code maintainability by providing a consistent, predictable structure.</p> | ||
| <h2>How to fix it</h2> | ||
| <p>Organize import declarations into the following groups, in this order:</p> | ||
| <ol> | ||
| <li> Module imports (e.g., <code>import module java.base;</code>) </li> | ||
| <li> On-demand package imports (e.g., <code>import javax.swing.text.*;</code>) </li> | ||
| <li> Single-type imports (e.g., <code>import java.util.List;</code>) </li> | ||
| <li> Static on-demand imports (e.g., <code>import static java.util.Collections.*;</code>) </li> | ||
| <li> Single-static imports (e.g., <code>import static java.util.regex.Pattern.compile;</code>) </li> | ||
| </ol> | ||
| <p>Separate each group with a blank line for better visual organization.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| import java.sql.Date; | ||
| import module java.base; | ||
| import static java.util.Collections.*; | ||
| import javax.swing.text.*; | ||
| import module java.desktop; | ||
| import static java.util.regex.Pattern.compile; | ||
| import java.util.List; | ||
|
|
||
| class Foo { | ||
| // ... | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| // Module imports | ||
| import module java.base; | ||
| import module java.desktop; | ||
|
|
||
| // On-demand package imports | ||
| import javax.swing.text.*; // resolves the ambiguity of the simple name Element | ||
|
|
||
| // Single-type imports | ||
| import java.sql.Date; // resolves the ambiguity of the simple name Date | ||
| import java.util.List; | ||
|
|
||
| // Static on-demand imports | ||
| import static java.util.Collections.*; | ||
|
|
||
| // Single-static imports | ||
| import static java.util.regex.Pattern.compile; | ||
|
|
||
| class Foo { | ||
| // ... | ||
| } | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li> <a href="https://docs.oracle.com/javase/specs/jls/se25/html/jls-7.html#jls-7.5">Java Language Specification - Import Declarations</a> </li> | ||
| <li> <a href="https://openjdk.org/jeps/511">JEP 511: Module Import Declarations</a> </li> | ||
| </ul> | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just noticed this. Right now the squiggly line is on the
importkeyword. It think it it would be nicer to underline the import itself. It can be done withreportIssue(importTree.qualifiedIdentifier(), message);and tested with// ^^^^^^^^^on the next line.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll do it, but as we've discussed, the whole functionality will be updated to QuickFix and single raise. So there's no real sense doing it.