Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package com.google.googlejavaformat.java;

import com.google.common.collect.ImmutableList;
import com.google.googlejavaformat.java.JavaInput.Tok;

/// Standard cleanup passes applied before formatting.
enum CleanupPass {
Expand All @@ -30,21 +31,25 @@ ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterE
AST_CLEANUPS {
@Override
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
return CleanupScanner.scan(cleanups.unit(), cleanups.contents(), cleanups.ranges());
return CleanupScanner.scan(
cleanups.unit(), cleanups.contents(), cleanups.toks(), cleanups.ranges());
}
},
/// Reorders modifiers into JLS order.
REORDER_MODIFIERS {
@Override
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
JavaInput javaInput = new JavaInput(cleanups.contents());
return ModifierOrderer.findModifierReplacements(javaInput, cleanups.ranges());
return ModifierOrderer.findModifierReplacements(cleanups.javaInput(), cleanups.ranges());
}
},
/// Reorders imports into canonical style order.
SORT_IMPORTS {
@Override
ImmutableList<Replacement> findReplacements(Cleanups cleanups) throws FormatterException {
ImmutableList<Tok> cached = cleanups.cachedToks();
if (cached != null) {
return ImportOrderer.findReplacements(cleanups.contents(), cleanups.style(), cached);
}
return ImportOrderer.findReplacements(cleanups.contents(), cleanups.style());
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,12 @@ final class CleanupScanner extends TreePathScanner<@Nullable Void, @Nullable Voi
private static final int IMPLICIT_CLASS = 1 << 19;

static ImmutableList<Replacement> scan(
JCCompilationUnit unit, String contents, Collection<Range<Integer>> ranges)
JCCompilationUnit unit,
String contents,
ImmutableList<Tok> toks,
Collection<Range<Integer>> ranges)
throws FormatterException {
RangeSet<Integer> targetRanges = TreeRangeSet.create(ranges);
ImmutableList<Tok> toks = JavaInput.buildToks(contents, ImmutableSet.of());
RangeSet<Integer> activeDeletions = TreeRangeSet.create();
new CleanupScanner(contents, unit, toks, targetRanges, activeDeletions).scan(unit, null);
if (activeDeletions.isEmpty()) {
Expand Down
38 changes: 34 additions & 4 deletions core/src/main/java/com/google/googlejavaformat/java/Cleanups.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.google.common.collect.Sets;
import com.google.common.collect.TreeRangeSet;
import com.google.googlejavaformat.java.JavaFormatterOptions.Style;
import com.google.googlejavaformat.java.JavaInput.Tok;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
import java.util.ArrayList;
Expand All @@ -43,11 +44,14 @@
final class Cleanups {

/// The cleaned contents, the requested character ranges remapped onto them (plus any modified
/// regions), and the javac unit for `contents` if it can be reused for formatting.
/// regions), and the javac unit, lexed tokens, and [JavaInput] for `contents` if they can be
/// reused for formatting.
record Result(
String contents,
Collection<Range<Integer>> characterRanges,
@Nullable JCCompilationUnit unit) {}
@Nullable JCCompilationUnit unit,
@Nullable ImmutableList<Tok> toks,
@Nullable JavaInput javaInput) {}

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

Expand Down Expand Up @@ -78,7 +82,7 @@ static Result apply(
throws FormatterException {
JavaInput.validateRanges(characterRanges, contents.length());
if (passes.isEmpty()) {
return new Result(contents, characterRanges, null);
return new Result(contents, characterRanges, null, null, null);
}
RangeSet<Integer> normalized = TreeRangeSet.create();
for (Range<Integer> range : characterRanges) {
Expand All @@ -98,12 +102,18 @@ static Result apply(
? ImmutableList.of(Range.closedOpen(0, 0))
: cleanups.ranges.asRanges();
return new Result(
cleanups.contents, resultRanges, cleanups.parsed == null ? null : cleanups.parsed.unit());
cleanups.contents,
resultRanges,
cleanups.parsed == null ? null : cleanups.parsed.unit(),
cleanups.toks,
cleanups.javaInput);
}

private String contents;
private ImmutableRangeSet<Integer> ranges;
private @Nullable Parsed parsed;
private @Nullable ImmutableList<Tok> toks;
private @Nullable JavaInput javaInput;
private final Style style;

private Cleanups(String contents, ImmutableRangeSet<Integer> ranges, Style style) {
Expand Down Expand Up @@ -148,6 +158,24 @@ Context context() throws FormatterException {
return parsed().context();
}

ImmutableList<Tok> toks() throws FormatterException {
if (toks == null) {
toks = JavaInput.buildToks(contents, ImmutableSet.of());
}
return toks;
}

@Nullable ImmutableList<Tok> cachedToks() {
return toks;
}

JavaInput javaInput() throws FormatterException {
if (javaInput == null) {
javaInput = new JavaInput(contents, toks());
}
return javaInput;
}

/// Applies a pass's replacements to the current contents, remapping requested ranges and adding
/// modified regions.
private void applyReplacements(List<Replacement> replacements) {
Expand All @@ -166,6 +194,8 @@ private void applyReplacements(List<Replacement> replacements) {
this.contents = edit.contents();
this.ranges = ImmutableRangeSet.copyOf(newRanges);
this.parsed = null;
this.toks = null;
this.javaInput = null;
}

/// Returns the range to reformat for the given span.
Expand Down
26 changes: 21 additions & 5 deletions core/src/main/java/com/google/googlejavaformat/java/Formatter.java
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,12 @@ String formatSource(
Edit.apply(
cleaned.contents(),
getFormatReplacements(
cleaned.contents(), cleaned.characterRanges(), options.cleanup(), cleaned.unit()));
cleaned.contents(),
cleaned.characterRanges(),
options.cleanup(),
cleaned.unit(),
cleaned.toks(),
cleaned.javaInput()));
if (reflowLongStrings) {
// Only reflow long strings in the requested ranges, mapped onto the formatted output.
return StringWrapper.wrap(
Expand Down Expand Up @@ -265,16 +270,27 @@ public ImmutableList<Replacement> getFormatReplacements(
ImmutableList<Replacement> getFormatReplacements(
String input, Collection<Range<Integer>> characterRanges, boolean reindent)
throws FormatterException {
return getFormatReplacements(input, characterRanges, reindent, /* unit= */ null);
return getFormatReplacements(
input,
characterRanges,
reindent,
/* unit= */ null,
/* cachedToks= */ null,
/* cachedJavaInput= */ null);
}

ImmutableList<Replacement> getFormatReplacements(
private ImmutableList<Replacement> getFormatReplacements(
String input,
Collection<Range<Integer>> characterRanges,
boolean reindent,
@Nullable JCCompilationUnit unit)
@Nullable JCCompilationUnit unit,
@Nullable ImmutableList<JavaInput.Tok> cachedToks,
@Nullable JavaInput cachedJavaInput)
throws FormatterException {
JavaInput javaInput = new JavaInput(input);
JavaInput javaInput =
cachedJavaInput != null
? cachedJavaInput
: (cachedToks != null ? new JavaInput(input, cachedToks) : new JavaInput(input));
if (unit != null) {
javaInput.setCompilationUnit(unit);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ public static String reorderImports(String text) throws FormatterException {
static ImmutableList<Replacement> findReplacements(String text, Style style)
throws FormatterException {
ImmutableList<Tok> toks = JavaInput.buildToks(text, CLASS_START);
return findReplacements(text, style, toks);
}

/// Variant of [#findReplacements(String, Style)] that reuses an already-lexed token stream.
static ImmutableList<Replacement> findReplacements(
String text, Style style, ImmutableList<Tok> toks) throws FormatterException {
return new ImportOrderer(text, toks, style).findReplacements();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,14 @@
/// @param text the input text
/// @throws FormatterException if the input cannot be parsed
JavaInput(String text) throws FormatterException {
this(text, buildToks(text, ImmutableSet.of()));
}

JavaInput(String text, ImmutableList<Tok> toks) {
this.text = checkNotNull(text);
setLines(ImmutableList.copyOf(Newlines.lineIterator(text)));
ImmutableList<Tok> toks = buildToks(text);
this.kN = getLast(toks).getIndex();
computeRanges(toks);
positionToColumnMap = makePositionToColumnMap(toks);
tokens = buildTokens(toks);
ImmutableRangeMap.Builder<Integer, Token> tokenLocations = ImmutableRangeMap.builder();
Expand Down Expand Up @@ -319,14 +324,6 @@
return positionToColumnMap;
}

/// Lex the input and build the list of toks.
private ImmutableList<Tok> buildToks(String text) throws FormatterException {
ImmutableList<Tok> toks = buildToks(text, ImmutableSet.of());
kN = getLast(toks).getIndex();
computeRanges(toks);
return toks;
}

/// Lex the input and build the list of toks.
///
/// @param text the text to be lexed.
Expand Down Expand Up @@ -447,7 +444,7 @@
// cannot be lexed without syntactic knowledge.
isToken = true;
isNumbered = true;
for (char c : tokText.toCharArray()) {

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient

Check warning on line 447 in core/src/main/java/com/google/googlejavaformat/java/JavaInput.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[LoopOverCharArray] toCharArray allocates a new array, using charAt is more efficient
strings.add(String.valueOf(c));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,8 +597,10 @@ class T {
public void parseReuseWhenNoEdits() throws Exception {
String input =
"""
import java.util.List;

class Test {
int x;
List<String> xs;
}
""";
Cleanups.Result result =
Expand All @@ -607,11 +609,13 @@ class Test {
ImmutableList.of(Range.closedOpen(0, input.length())),
Style.GOOGLE,
Cleanups.enabledPasses(
/* cleanup= */ false,
/* cleanup= */ true,
/* removeUnusedImports= */ true,
/* reorderModifiers= */ false,
/* sortImports= */ false));
/* reorderModifiers= */ true,
/* sortImports= */ true));
assertThat(result.unit()).isNotNull();
assertThat(result.toks()).isNotNull();
assertThat(result.javaInput()).isNotNull();
assertThat(result.contents()).isEqualTo(input);
}

Expand All @@ -634,6 +638,8 @@ class Test {
/* reorderModifiers= */ true,
/* sortImports= */ false));
assertThat(result.unit()).isNull();
assertThat(result.toks()).isNull();
assertThat(result.javaInput()).isNull();
assertThat(result.contents()).contains("public static int x;");
}

Expand Down Expand Up @@ -697,10 +703,72 @@ void f(boolean a) {
/* reorderModifiers= */ false,
/* sortImports= */ false));
assertThat(result.unit()).isNotNull();
assertThat(result.toks()).isNotNull();
assertThat(result.javaInput()).isNull();
assertThat(result.contents()).doesNotContain("ArrayList");
assertThat(result.contents()).contains("if (a) {");
}

@Test
public void adjacentUnusedImportAndRedundantSemicolon() throws Exception {
String input =
"""
package test;

import java.util.ArrayList;;

class Test {}
""";
Cleanups.Result result =
Cleanups.apply(
input,
ImmutableList.of(Range.closedOpen(0, input.length())),
Style.GOOGLE,
Cleanups.enabledPasses(
/* cleanup= */ true,
/* removeUnusedImports= */ true,
/* reorderModifiers= */ true,
/* sortImports= */ true));
assertThat(result.unit()).isNull();
assertThat(result.toks()).isNotNull();
assertThat(result.javaInput()).isNotNull();
assertThat(result.contents())
.isEqualTo(
"""
package test;


class Test {}
""");
}

@Test
public void fixImportsOnlyDoesNotBuildJavaInput() throws Exception {
String input =
"""
import java.util.List;
import java.util.Set;

class Test {
List<Set<String>> xs;
}
""";
Cleanups.Result result =
Cleanups.apply(
input,
ImmutableList.of(Range.closedOpen(0, input.length())),
Style.GOOGLE,
Cleanups.enabledPasses(
/* cleanup= */ false,
/* removeUnusedImports= */ true,
/* reorderModifiers= */ false,
/* sortImports= */ true));
assertThat(result.unit()).isNotNull();
assertThat(result.toks()).isNull();
assertThat(result.javaInput()).isNull();
assertThat(result.contents()).isEqualTo(input);
}

@Test
public void emptyString() throws Exception {
assertThat(new Formatter().formatSource("")).isEqualTo("\n");
Expand Down
Loading