|
| 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 | +} |
0 commit comments