Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 3 additions & 62 deletions core/src/main/java/com/google/googlejavaformat/java/Cleanups.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

package com.google.googlejavaformat.java;

import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Math.max;
import static java.lang.Math.min;

Expand Down Expand Up @@ -50,57 +49,6 @@ record Result(
Collection<Range<Integer>> characterRanges,
@Nullable JCCompilationUnit unit) {}

/// One replacement: `[inStart, inEnd)` in the old contents became `[outStart, outEnd)`.
private record Span(int inStart, int inEnd, int outStart, int outEnd) {}

/// The result of applying sorted, non-overlapping replacements to some text.
private record Edit(String contents, ImmutableList<Span> spans) {

/// Applies sorted, non-overlapping replacements to `contents`.
static Edit apply(String contents, List<Replacement> replacements) {
StringBuilder sb = new StringBuilder(contents.length());
ImmutableList.Builder<Span> spans =
ImmutableList.builderWithExpectedSize(replacements.size());
int cursor = 0;
for (Replacement replacement : replacements) {
Range<Integer> range = replacement.replaceRange();
int inStart = range.lowerEndpoint();
int inEnd = range.upperEndpoint();
checkArgument(
inStart >= cursor,
"Replacements must be sorted and non-overlapping, but %s overlaps previous end %s",
range,
cursor);
sb.append(contents, cursor, inStart);
int outStart = sb.length();
sb.append(replacement.replacementString());
int outEnd = sb.length();
spans.add(new Span(inStart, inEnd, outStart, outEnd));
cursor = inEnd;
}
sb.append(contents, cursor, contents.length());
return new Edit(sb.toString(), spans.build());
}

/// Maps an offset in the old contents to the corresponding offset in the new contents.
///
/// Offsets before a span are unchanged relative to the previous span; offsets inside a span are
/// clamped to its replacement text; offsets after all spans are shifted by the final span.
int map(int offset) {
Span prev = null;
for (Span span : spans) {
if (offset < span.inStart()) {
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
}
if (offset <= span.inEnd()) {
return span.outStart() + min(offset - span.inStart(), span.outEnd() - span.outStart());
}
prev = span;
}
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
}
}

private record Parsed(Context context, JCCompilationUnit unit) {}

/// Returns the enabled passes for formatting or fixing imports.
Expand Down Expand Up @@ -207,15 +155,8 @@ private void applyReplacements(List<Replacement> replacements) {
return;
}
Edit edit = Edit.apply(contents, replacements);
RangeSet<Integer> newRanges = TreeRangeSet.create();
for (Range<Integer> range : ranges.asRanges()) {
int mappedStart = edit.map(range.lowerEndpoint());
int mappedEnd = edit.map(range.upperEndpoint());
if (mappedStart < mappedEnd) {
newRanges.add(Range.closedOpen(mappedStart, mappedEnd));
}
}
for (Span span : edit.spans()) {
RangeSet<Integer> newRanges = TreeRangeSet.create(edit.mapRanges(ranges.asRanges()));
for (Edit.Span span : edit.spans()) {
Range<Integer> r = reformatRange(span, edit.contents());
if (!r.isEmpty()) {
newRanges.add(r);
Expand All @@ -228,7 +169,7 @@ private void applyReplacements(List<Replacement> replacements) {
}

/// Returns the range to reformat for the given span.
private static Range<Integer> reformatRange(Span span, String contents) {
private static Range<Integer> reformatRange(Edit.Span span, String contents) {
if (span.outStart() == span.outEnd()) {
return deletionReformatRange(contents, span.outStart());
}
Expand Down
108 changes: 108 additions & 0 deletions core/src/main/java/com/google/googlejavaformat/java/Edit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Copyright 2026 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

package com.google.googlejavaformat.java;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.commonPrefix;
import static com.google.common.base.Strings.commonSuffix;
import static java.lang.Math.min;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
import java.nio.CharBuffer;
import java.util.Collection;
import java.util.List;

/// The result of applying sorted, non-overlapping replacements to some text, which can map offsets
/// in the old text to offsets in the new text.
record Edit(String contents, ImmutableList<Edit.Span> spans) {

/// One replacement: `[inStart, inEnd)` in the old contents became `[outStart, outEnd)`.
record Span(int inStart, int inEnd, int outStart, int outEnd) {}

/// Applies sorted, non-overlapping replacements to `contents`.
static Edit apply(String contents, List<Replacement> replacements) {
StringBuilder sb = new StringBuilder(contents.length());
ImmutableList.Builder<Span> spans = ImmutableList.builderWithExpectedSize(replacements.size());
int cursor = 0;
for (Replacement replacement : replacements) {
Range<Integer> range = replacement.replaceRange();
int inStart = range.lowerEndpoint();
int inEnd = range.upperEndpoint();
checkArgument(
inStart >= cursor,
"Replacements must be sorted and non-overlapping, but %s overlaps previous end %s",
range,
cursor);
sb.append(contents, cursor, inStart);
String replacementString = replacement.replacementString();
int outStart = sb.length();
sb.append(replacementString);
int outEnd = sb.length();
// Trim any unchanged prefix and suffix so coarse replacements (such as reformatting an entire
// statement) don't treat unchanged tokens at the start or end of the replacement as part of
// the modified span.
int prefix =
commonPrefix(CharBuffer.wrap(contents, inStart, inEnd), replacementString).length();
int suffix =
commonSuffix(
CharBuffer.wrap(contents, inStart + prefix, inEnd),
CharBuffer.wrap(replacementString, prefix, replacementString.length()))
.length();
if (inStart + prefix < inEnd - suffix || outStart + prefix < outEnd - suffix) {
spans.add(new Span(inStart + prefix, inEnd - suffix, outStart + prefix, outEnd - suffix));
}
cursor = inEnd;
}
sb.append(contents, cursor, contents.length());
return new Edit(sb.toString(), spans.build());
}

/// Maps an offset in the old contents to the corresponding offset in the new contents.
///
/// Offsets in unmodified text are shifted by the cumulative length change of preceding
/// replacements. Offsets inside a replaced range `[inStart, inEnd)` are shifted relative to
/// `inStart` and clamped to `outEnd` if the replacement is shorter than the original range.
int map(int offset) {
int shift = 0;
for (Span span : spans) {
if (offset < span.inStart()) {
return offset + shift;
}
if (offset < span.inEnd()) {
return min(offset + shift, span.outEnd());
}
shift = span.outEnd() - span.inEnd();
}
return offset + shift;
}

/// Maps ranges in the old contents to the corresponding ranges in the new contents, dropping
/// ranges that become empty.
ImmutableRangeSet<Integer> mapRanges(Collection<Range<Integer>> ranges) {
RangeSet<Integer> result = TreeRangeSet.create();
for (Range<Integer> range : ranges) {
int start = map(range.lowerEndpoint());
int end = map(range.upperEndpoint());
if (start < end) {
result.add(Range.closedOpen(start, end));
}
}
return ImmutableRangeSet.copyOf(result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,15 +189,20 @@ String formatSource(
Cleanups.enabledPasses(
options.cleanup(), removeUnusedImports, options.reorderModifiers(), sortImports);
Cleanups.Result cleaned = Cleanups.apply(input, characterRanges, options.style(), passes);
String formatted =
JavaOutput.applyReplacements(
Edit formatted =
Edit.apply(
cleaned.contents(),
getFormatReplacements(
cleaned.contents(), cleaned.characterRanges(), options.cleanup(), cleaned.unit()));
if (reflowLongStrings) {
formatted = StringWrapper.wrap(options.maxLineLength(), formatted, this);
// Only reflow long strings in the requested ranges, mapped onto the formatted output.
return StringWrapper.wrap(
options.maxLineLength(),
formatted.contents(),
this,
formatted.mapRanges(cleaned.characterRanges()));
}
return formatted;
return formatted.contents();
}

/// Formats an input string (a Java compilation unit) and fixes imports.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
import com.google.common.base.CharMatcher;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeMap;
import com.google.googlejavaformat.Newlines;
import com.sun.source.tree.BinaryTree;
Expand Down Expand Up @@ -58,20 +60,36 @@ public static String wrap(String input, Formatter formatter) throws FormatterExc
/// Reflows string literals in the given Java source code that extend past the given column limit.
static String wrap(final int columnLimit, String input, Formatter formatter)
throws FormatterException {
return wrap(
columnLimit, input, formatter, ImmutableRangeSet.of(Range.closedOpen(0, input.length())));
}

/// Reflows string literals in the given character ranges of the given Java source code that
/// extend past the given column limit.
static String wrap(
final int columnLimit, String input, Formatter formatter, RangeSet<Integer> characterRanges)
throws FormatterException {
JavaFormatterOptions options = formatter.options();
if (!needWrapping(columnLimit, input, options)) {
// fast path
return input;
}

TreeRangeMap<Integer, String> replacements = getReflowReplacements(columnLimit, input, options);
String firstPass = formatter.formatSource(input, replacements.asMapOfRanges().keySet());
TreeRangeMap<Integer, String> replacements =
getReflowReplacements(columnLimit, input, options, characterRanges);
if (replacements.asMapOfRanges().isEmpty()) {
return input;
}
Edit firstPass =
Edit.apply(
input, formatter.getFormatReplacements(input, replacements.asMapOfRanges().keySet()));

if (!firstPass.equals(input)) {
if (!firstPass.contents().equals(input)) {
// If formatting the replacement ranges resulted in a change, recalculate the replacements on
// the updated input.
input = firstPass;
replacements = getReflowReplacements(columnLimit, input, options);
input = firstPass.contents();
characterRanges = firstPass.mapRanges(characterRanges.asRanges());
replacements = getReflowReplacements(columnLimit, input, options, characterRanges);
}

String result = applyReplacements(input, replacements);
Expand Down Expand Up @@ -111,24 +129,34 @@ private static FormatterException somethingHasGoneTerriblyWrong(
}

private static TreeRangeMap<Integer, String> getReflowReplacements(
int columnLimit, final String input, JavaFormatterOptions options) throws FormatterException {
return new Reflower(columnLimit, input, options).getReflowReplacements();
int columnLimit,
final String input,
JavaFormatterOptions options,
RangeSet<Integer> characterRanges)
throws FormatterException {
return new Reflower(columnLimit, input, options, characterRanges).getReflowReplacements();
}

private static class Reflower {

private final String input;
private final int columnLimit;
private final JavaFormatterOptions options;
private final RangeSet<Integer> characterRanges;
private final String separator;
private final JCTree.JCCompilationUnit unit;
private final Position.LineMap lineMap;

Reflower(int columnLimit, String input, JavaFormatterOptions options)
Reflower(
int columnLimit,
String input,
JavaFormatterOptions options,
RangeSet<Integer> characterRanges)
throws FormatterException {
this.columnLimit = columnLimit;
this.input = input;
this.options = options;
this.characterRanges = characterRanges;
this.separator = Newlines.guessLineSeparator(input);
this.unit = parse(input, /* allowStringFolding= */ false);
this.lineMap = unit.getLineMap();
Expand Down Expand Up @@ -170,6 +198,10 @@ public Void visitLiteral(LiteralTree literalTree, Void aVoid) {
return null;
}
int endPosition = getEndPosition(literalTree, unit);
if (!characterRanges.intersects(
Range.closedOpen(getStartPosition(literalTree), endPosition))) {
return null;
}
int lineEnd = endPosition;
while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
lineEnd++;
Expand Down
Loading
Loading