google-java-format icon indicating copy to clipboard operation
google-java-format copied to clipboard

Support Module Import Declarations (JEP 476, JDK 23)

Open sebastiaanspeck opened this issue 1 year ago • 2 comments

Consider the following code:

// this will import e.g. all the classes from package java.util, java.util.stream, java.io, java.lang, java.nio.file
import module java.base;

When trying to use google-java-format 1.24.0, this results in: com.google.googlejavaformat.java.FormatterException: 2:1: error: expected token: 'module'; generated java instead

sebastiaanspeck avatar Dec 24 '24 06:12 sebastiaanspeck

Note that this is currently a preview feature, there's a draft JEP to finalize the feature in Java 25: https://openjdk.org/jeps/8344700

cushon avatar Mar 23 '25 21:03 cushon

I wonder where GJF will put import MODULE; declarations in relation to the static and non-static block as described in https://google.github.io/styleguide/javaguide.html#s3.3-import-statements

3.3.3 Ordering and spacing Imports are ordered as follows:

  1. All static imports in a single block.
  2. All non-static imports in a single block.

If there are both static and non-static imports, a single blank line separates the two blocks. There are no other blank lines between import statements.

sormuras avatar Mar 26 '25 14:03 sormuras

Finalized as "JEP 511: Module Import Declarations" in Java 25.

sormuras avatar Jul 15 '25 05:07 sormuras

The style guide update for module imports is still TBD, but that should happen in time for the Java 25 GA.

It's possible it will discourage module imports in favor of single-type imports (similar to how wildcard imports are already discouraged).

But either way, google-java-format should support the syntax for files that use it.

cushon avatar Jul 16 '25 20:07 cushon

I pushed a release that adds support for import module.

The style guide will be updated to disallow import module (similar to how wildcard imports are disallowed): https://github.com/google/styleguide/pull/946

cushon avatar Oct 13 '25 13:10 cushon

Great news, Liam.

The guide will disallow them, but gjf will keep them? I.e. gjf will not expand them to normal type imports?

sormuras avatar Oct 13 '25 15:10 sormuras

g-j-f will preserve them.

It doesn't have enough information to expand them even if we wanted to do that in the formatter. That might be something we'd add to Error Prone eventually, similar to https://errorprone.info/bugpattern/WildcardImport.

cushon avatar Oct 13 '25 15:10 cushon