Skip to content

Commit 633ce6b

Browse files
cushongoogle-java-format Team
authored andcommitted
Run unused-import removal, modifier reordering, and import sorting as a single pre-formatting pipeline.
Consolidate unused-import removal, modifier reordering, and import sorting into a unified Cleanups pass that runs before core layout. Unused imports are removed and imports are sorted before formatting. When no non-whitespace pass modifies the input, the parsed compilation unit is reused directly during formatting. RELNOTES=`Formatter.getFormatReplacements` is now strictly whitespace-only and no longer reorders modifiers; use `Formatter.formatSource(String, Collection<Range<Integer>>)` to format character ranges with modifier reordering (or `JavaFormatterOptions.builder().reorderModifiers(false)` to disable modifier reordering). PiperOrigin-RevId: 1002946984
1 parent ee81376 commit 633ce6b

7 files changed

Lines changed: 658 additions & 45 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright 2026 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.googlejavaformat.java;
16+
17+
import com.google.common.collect.ImmutableList;
18+
19+
/// Standard cleanup passes applied before formatting.
20+
enum CleanupPass {
21+
/// Removes unused imports.
22+
REMOVE_UNUSED_IMPORTS {
23+
@Override
24+
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
25+
return RemoveUnusedImports.findUnusedImports(
26+
cleanups.context(), cleanups.unit(), cleanups.contents());
27+
}
28+
},
29+
/// Reorders modifiers into JLS order.
30+
REORDER_MODIFIERS {
31+
@Override
32+
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
33+
JavaInput javaInput = new JavaInput(cleanups.contents());
34+
return ModifierOrderer.findModifierReplacements(javaInput, cleanups.ranges());
35+
}
36+
},
37+
/// Reorders imports into canonical style order.
38+
SORT_IMPORTS {
39+
@Override
40+
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
41+
return ImportOrderer.findReplacements(cleanups.contents(), cleanups.style());
42+
}
43+
};
44+
45+
/// Finds replacements to apply to the current pipeline state. The returned replacements must be
46+
/// relative to `cleanups.contents()`, sorted by start position, and non-overlapping.
47+
abstract ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException;
48+
}
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
/*
2+
* Copyright 2026 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.googlejavaformat.java;
16+
17+
import static com.google.common.base.Preconditions.checkArgument;
18+
import static java.lang.Math.max;
19+
import static java.lang.Math.min;
20+
21+
import com.google.common.collect.ImmutableList;
22+
import com.google.common.collect.ImmutableRangeSet;
23+
import com.google.common.collect.ImmutableSet;
24+
import com.google.common.collect.Range;
25+
import com.google.common.collect.RangeSet;
26+
import com.google.common.collect.Sets;
27+
import com.google.common.collect.TreeRangeSet;
28+
import com.google.googlejavaformat.java.JavaFormatterOptions.Style;
29+
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
30+
import com.sun.tools.javac.util.Context;
31+
import java.util.ArrayList;
32+
import java.util.Collection;
33+
import java.util.EnumSet;
34+
import java.util.List;
35+
import javax.tools.Diagnostic;
36+
import javax.tools.JavaFileObject;
37+
import org.jspecify.annotations.Nullable;
38+
39+
/// Applies non-whitespace cleanups before core formatting.
40+
///
41+
/// Each pass produces replacements relative to the current contents; the requested character ranges
42+
/// are remapped through every pass so formatting still targets the code the caller selected.
43+
final class Cleanups {
44+
45+
/// The cleaned contents, the requested character ranges remapped onto them (plus any modified
46+
/// regions), and the javac unit for `contents` if it can be reused for formatting.
47+
record Result(
48+
String contents,
49+
Collection<Range<Integer>> characterRanges,
50+
@Nullable JCCompilationUnit unit) {}
51+
52+
/// One replacement: `[inStart, inEnd)` in the old contents became `[outStart, outEnd)`.
53+
private record Span(int inStart, int inEnd, int outStart, int outEnd) {}
54+
55+
/// The result of applying sorted, non-overlapping replacements to some text.
56+
private record Edit(String contents, ImmutableList<Span> spans) {
57+
58+
/// Applies sorted, non-overlapping replacements to `contents`.
59+
static Edit apply(String contents, List<Replacement> replacements) {
60+
StringBuilder sb = new StringBuilder(contents.length());
61+
ImmutableList.Builder<Span> spans =
62+
ImmutableList.builderWithExpectedSize(replacements.size());
63+
int cursor = 0;
64+
for (Replacement replacement : replacements) {
65+
Range<Integer> range = replacement.replaceRange();
66+
int inStart = range.lowerEndpoint();
67+
int inEnd = range.upperEndpoint();
68+
checkArgument(
69+
inStart >= cursor,
70+
"Replacements must be sorted and non-overlapping, but %s overlaps previous end %s",
71+
range,
72+
cursor);
73+
sb.append(contents, cursor, inStart);
74+
int outStart = sb.length();
75+
sb.append(replacement.replacementString());
76+
int outEnd = sb.length();
77+
spans.add(new Span(inStart, inEnd, outStart, outEnd));
78+
cursor = inEnd;
79+
}
80+
sb.append(contents, cursor, contents.length());
81+
return new Edit(sb.toString(), spans.build());
82+
}
83+
84+
/// Maps an offset in the old contents to the corresponding offset in the new contents.
85+
///
86+
/// Offsets before a span are unchanged relative to the previous span; offsets inside a span are
87+
/// clamped to its replacement text; offsets after all spans are shifted by the final span.
88+
int map(int offset) {
89+
Span prev = null;
90+
for (Span span : spans) {
91+
if (offset < span.inStart()) {
92+
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
93+
}
94+
if (offset <= span.inEnd()) {
95+
return span.outStart() + min(offset - span.inStart(), span.outEnd() - span.outStart());
96+
}
97+
prev = span;
98+
}
99+
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
100+
}
101+
}
102+
103+
private record Parsed(Context context, JCCompilationUnit unit) {}
104+
105+
/// Returns the enabled passes for formatting or fixing imports.
106+
static ImmutableSet<CleanupPass> enabledPasses(
107+
boolean removeUnusedImports, boolean reorderModifiers, boolean sortImports) {
108+
EnumSet<CleanupPass> passes = EnumSet.noneOf(CleanupPass.class);
109+
if (removeUnusedImports) {
110+
passes.add(CleanupPass.REMOVE_UNUSED_IMPORTS);
111+
}
112+
if (reorderModifiers) {
113+
passes.add(CleanupPass.REORDER_MODIFIERS);
114+
}
115+
if (sortImports) {
116+
passes.add(CleanupPass.SORT_IMPORTS);
117+
}
118+
return Sets.immutableEnumSet(passes);
119+
}
120+
121+
static Result apply(
122+
String contents,
123+
Collection<Range<Integer>> characterRanges,
124+
Style style,
125+
ImmutableSet<CleanupPass> passes)
126+
throws FormatterException {
127+
JavaInput.validateRanges(characterRanges, contents.length());
128+
if (passes.isEmpty()) {
129+
return new Result(contents, characterRanges, null);
130+
}
131+
RangeSet<Integer> normalized = TreeRangeSet.create();
132+
for (Range<Integer> range : characterRanges) {
133+
normalized.add(
134+
range.isEmpty() && range.lowerEndpoint() < contents.length()
135+
? Range.closedOpen(range.lowerEndpoint(), range.lowerEndpoint() + 1)
136+
: range);
137+
}
138+
Cleanups cleanups = new Cleanups(contents, ImmutableRangeSet.copyOf(normalized), style);
139+
for (CleanupPass pass : passes) {
140+
cleanups.applyReplacements(pass.findReplacements(cleanups));
141+
}
142+
return cleanups.result();
143+
}
144+
145+
private String contents;
146+
private ImmutableRangeSet<Integer> ranges;
147+
private @Nullable Parsed parsed;
148+
private final Style style;
149+
150+
private Cleanups(String contents, ImmutableRangeSet<Integer> ranges, Style style) {
151+
this.contents = contents;
152+
this.ranges = ranges;
153+
this.style = style;
154+
}
155+
156+
String contents() {
157+
return contents;
158+
}
159+
160+
ImmutableSet<Range<Integer>> ranges() {
161+
return ranges.asRanges();
162+
}
163+
164+
Style style() {
165+
return style;
166+
}
167+
168+
private Parsed parsed() throws FormatterException {
169+
if (parsed != null) {
170+
return parsed;
171+
}
172+
Context ctx = new Context();
173+
List<Diagnostic<? extends JavaFileObject>> errorDiagnostics = new ArrayList<>();
174+
JCCompilationUnit cu =
175+
Trees.parse(ctx, errorDiagnostics, /* allowStringFolding= */ false, contents);
176+
if (!errorDiagnostics.isEmpty()) {
177+
throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
178+
}
179+
Parsed p = new Parsed(ctx, cu);
180+
this.parsed = p;
181+
return p;
182+
}
183+
184+
JCCompilationUnit unit() throws FormatterException {
185+
return parsed().unit();
186+
}
187+
188+
Context context() throws FormatterException {
189+
return parsed().context();
190+
}
191+
192+
Result result() {
193+
return new Result(contents, ranges.asRanges(), parsed == null ? null : parsed.unit());
194+
}
195+
196+
/// Applies a pass's replacements to the current contents, remapping requested ranges and adding
197+
/// modified regions.
198+
private void applyReplacements(List<Replacement> replacements) {
199+
if (replacements.isEmpty()) {
200+
return;
201+
}
202+
Edit edit = Edit.apply(contents, replacements);
203+
RangeSet<Integer> newRanges = TreeRangeSet.create();
204+
for (Range<Integer> range : ranges.asRanges()) {
205+
int mappedStart = edit.map(range.lowerEndpoint());
206+
int mappedEnd = edit.map(range.upperEndpoint());
207+
if (mappedStart < mappedEnd) {
208+
newRanges.add(Range.closedOpen(mappedStart, mappedEnd));
209+
}
210+
}
211+
for (Span span : edit.spans()) {
212+
Range<Integer> r = reformatRange(span, edit.contents());
213+
if (!r.isEmpty()) {
214+
newRanges.add(r);
215+
}
216+
}
217+
218+
this.contents = edit.contents();
219+
this.ranges = ImmutableRangeSet.copyOf(newRanges);
220+
this.parsed = null;
221+
}
222+
223+
/// Returns the range to reformat for the given span.
224+
private static Range<Integer> reformatRange(Span span, String contents) {
225+
int start = span.outStart();
226+
int end = span.outEnd();
227+
if (start == end && !contents.isEmpty()) {
228+
start = max(0, start - 1);
229+
end = min(contents.length(), end + 1);
230+
}
231+
return start < end ? Range.closedOpen(start, end) : Range.closedOpen(0, 0);
232+
}
233+
}

‎core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -66,31 +66,28 @@ static Result create(
6666
public Result call() {
6767
try {
6868
if (parameters.fixImportsOnly()) {
69-
return Result.create(path, input, fixImports(input), /* exception= */ null);
69+
return Result.create(
70+
path,
71+
input,
72+
Formatter.fixImports(
73+
input, options.style(), parameters.removeUnusedImports(), parameters.sortImports()),
74+
/* exception= */ null);
7075
}
7176

7277
Formatter formatter = new Formatter(options);
73-
String formatted = formatter.formatSource(input, characterRanges(input).asRanges());
74-
formatted = fixImports(formatted);
75-
if (parameters.reflowLongStrings()) {
76-
formatted = StringWrapper.wrap(options.maxLineLength(), formatted, formatter);
77-
}
78+
String formatted =
79+
formatter.formatSource(
80+
input,
81+
characterRanges(input).asRanges(),
82+
parameters.removeUnusedImports(),
83+
parameters.sortImports(),
84+
parameters.reflowLongStrings());
7885
return Result.create(path, input, formatted, /* exception= */ null);
7986
} catch (FormatterException e) {
8087
return Result.create(path, input, /* output= */ null, e);
8188
}
8289
}
8390

84-
private String fixImports(String input) throws FormatterException {
85-
if (parameters.removeUnusedImports()) {
86-
input = RemoveUnusedImports.removeUnusedImports(input);
87-
}
88-
if (parameters.sortImports()) {
89-
input = ImportOrderer.reorderImports(input, options.style());
90-
}
91-
return input;
92-
}
93-
9491
private RangeSet<Integer> characterRanges(String input) {
9592
final RangeSet<Integer> characterRanges = TreeRangeSet.create();
9693

0 commit comments

Comments
 (0)