Skip to content

A comment between imports fails the whole file: "Imports not contiguous" #39

Description

@abashev

What

Reported upstream as google/google-java-format#424 (a javadoc between two imports, 2019) and google/google-java-format#546 (the same message through a Maven plugin, 2020). It is also one of the samples in palantir/palantir-java-format#789. It reproduces here on main:

import b.B;

// why we need A
import a.A;

class T {
    A a;
    B b;
}

open-java-format T.java fails with T.java:error: Imports not contiguous (perhaps a comment separates them?) and exit code 2, so nothing in the file gets formatted. A /* */ or javadoc comment between imports fails the same way. A // comment on the line right under an import is accepted: it is kept as that import's trailing comment and moves with it.

The other sample in palantir#789, a lone ; between two imports, is not ours to handle: javac 21 rejects it with "extraneous semicolon".

Why it happens

ImportOrderer.scanImports reads imports while the next token is import. After each one it takes the rest of the line and the // comments directly under it. A blank line followed by a comment, or a block comment, ends the scan; reorderImports then finds another import further down and throws.

Fix

When comments between two imports are followed by another import, keep them as the leading text of that import, so they move with it when the imports are sorted. Comments after the last import still belong to what follows, and trailing // comments stay as they are.

Only files that fail today change.

Done when

  • the file above formats, // why we need A stays directly above import a.A;, and a second run changes nothing;
  • ImportOrdererTest covers a line comment, a block comment and a javadoc between imports, and a comment after the last import;
  • a corpus run shows no change for files that format today.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions