Skip to content

IllegalImport: new property illegalModules to cover module imports #18207

@stoyanK7

Description

@stoyanK7

Part of issue


I have read check documentation: https://checkstyle.org/checks/imports/illegalimport.html
I am using the latest checkstyle generated from the master branch via mvn clean package -Passembly
I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

How it works now

$ javac -version
javac 25.0.1

$ javac Test.java
# no output, because file compiles successifully

$ cat Test.java
import module java.sql;  // I want to forbid importation of this module
import module java.logging;

class Test {}

$ cat config.xml
<!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
  <module name="TreeWalker">
    <module name="IllegalImport">
      <property name="illegalPkgs" value="java.sql"/>
      <property name="illegalClasses" value="java.sql"/>
    </module>
  </module>
</module>

$ RUN_LOCALE="-Duser.language=en -Duser.country=US"
$ java $RUN_LOCALE -jar ~/Documents/github/checkstyle/target/checkstyle-12.2.0-SNAPSHOT-all.jar -c config.xml Test.java
Starting audit...
Audit done.

Is your feature request related to a problem? Please describe.
Yes. IllegalImport currently only processes IMPORT and STATIC_IMPORT tokens, but not MODULE_IMPORT:

@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
}

In other words, IllegalImport does not enforce illegal imports for module import syntax (import module ...).

Describe the solution you'd like
I would like to have a dedicated illegalModules property, where I can describe list of module names I want to reject. It must behave the same way as the illegalPkgs and illegalClasses properties:
If the regexp property is set to false, entries are treated as exact module names (java.base, java.logging). If regexp property is set to true, entries are treated as regular expressions that are matched against module names.

I imagine a configuration like:

<module name="IllegalImport">
  <property name="illegalModules" value="java.sql"/>
</module>

that flags the following code:

import module java.sql;   // violation

with a violation like this:

[ERROR] /tmp/Test.java:1:1: Illegal import - java.sql. [IllegalImport]
Audit done.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions