diff --git a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java index eb6682dc5..81cffa09f 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java @@ -19,8 +19,9 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ForwardingListMultimap; import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; +import com.google.common.collect.ListMultimap; import com.palantir.javaformat.Indent.Const; import com.palantir.javaformat.Input.Tok; import com.palantir.javaformat.doc.Break; @@ -521,13 +522,32 @@ private static int getI(Input.Token token) { public record OpsOutput(List ops, InputMetadata inputMetadata) {} + /** + * An {@link ArrayListMultimap} whose {@link #get} of a key without values returns {@link List#of()}. {@link #build} + * asks for the ops to insert at every op and most have none, and {@link ArrayListMultimap#get} would make a new + * empty list and a view of it for each. The list returned for such a key cannot be added to. + */ + private static final class SparseListMultimap extends ForwardingListMultimap { + private final ArrayListMultimap delegate = ArrayListMultimap.create(); + + @Override + protected ListMultimap delegate() { + return delegate; + } + + @Override + public List get(K key) { + return delegate.containsKey(key) ? delegate.get(key) : List.of(); + } + } + /** Build a list of {@link Op}s from the {@code OpsBuilder}. */ public OpsOutput build() { markForPartialFormat(); // Rewrite the ops to insert comments. - Multimap tokOps = ArrayListMultimap.create(); + var tokOps = new SparseListMultimap(); // The room after a string literal for the NON-NLS markers written on its line, see Comment.makeNonNlsMarkers. - var reservations = ArrayListMultimap.create(); + var reservations = new SparseListMultimap(); var tokenOps = new HashMap(); Map tokenByIndex = null; int opsN = ops.size(); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java index c447e6f04..61331f893 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java @@ -17,7 +17,6 @@ package com.palantir.javaformat.doc; import com.google.common.collect.Range; -import com.google.errorprone.annotations.Immutable; import com.palantir.javaformat.CommentsHelper; import com.palantir.javaformat.Indent; import com.palantir.javaformat.Op; @@ -27,7 +26,6 @@ import org.immutables.value.Value; /** A leaf node in a {@link Doc} for an optional break. */ -@Immutable @Value.Immutable public abstract class Break extends Doc implements Op { public abstract FillMode fillMode(); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java index 57d6cbfd6..8d3a43056 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java @@ -16,7 +16,6 @@ package com.palantir.javaformat.doc; -import com.google.common.base.Suppliers; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Range; import com.palantir.javaformat.CommentsHelper; @@ -24,6 +23,7 @@ import com.palantir.javaformat.Op; import com.palantir.javaformat.OpsBuilder; import com.palantir.javaformat.Output; +import org.jspecify.annotations.Nullable; /** * {@link com.palantir.javaformat.java.JavaInputAstVisitor JavaInputAstVisitor} outputs a sequence of {@link Op}s using @@ -37,14 +37,15 @@ public abstract class Doc extends HasUniqueId { static final Range EMPTY_RANGE = Range.closedOpen(-1, -1); static final DiscreteDomain INTEGERS = DiscreteDomain.integers(); - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedWidth = Suppliers.memoize(this::computeWidth)::get; + // The width, flat value and range, computed when first asked for, once the doc is complete. The width is NaN until + // then, which computeWidth never returns. + private float memoizedWidth = Float.NaN; - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedFlat = Suppliers.memoize(this::computeFlat)::get; + @Nullable + private String memoizedFlat; - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier> memoizedRange = Suppliers.memoize(this::computeRange)::get; + @Nullable + private Range memoizedRange; /** * Return the width of a {@code Doc}, or {@code Float.POSITIVE_INFINITY} if it must be broken. @@ -52,7 +53,10 @@ public abstract class Doc extends HasUniqueId { * @return the width */ final float getWidth() { - return memoizedWidth.get(); + if (Float.isNaN(memoizedWidth)) { + memoizedWidth = computeWidth(); + } + return memoizedWidth; } /** @@ -62,11 +66,17 @@ final float getWidth() { * @return the flat-string value */ public final String getFlat() { - return memoizedFlat.get(); + if (memoizedFlat == null) { + memoizedFlat = computeFlat(); + } + return memoizedFlat; } final Range range() { - return memoizedRange.get(); + if (memoizedRange == null) { + memoizedRange = computeRange(); + } + return memoizedRange; } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java deleted file mode 100644 index 274e4eedc..000000000 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. - * - * 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.palantir.javaformat.doc; - -import com.google.errorprone.annotations.Immutable; -import java.util.function.Supplier; - -@Immutable -interface ImmutableSupplier extends Supplier {} diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java index 98197c055..8790cd8df 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java @@ -20,7 +20,6 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.common.base.Suppliers; import com.google.common.collect.Range; import com.palantir.javaformat.BreakBehaviour; import com.palantir.javaformat.BreakBehaviour.BreakOnlyIfInnerLevelsThenFitOnOneLine; @@ -60,12 +59,12 @@ public final class Level extends Doc { private final List docs = new ArrayList<>(); // The elements of the level. - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedSplitsBreaks = - Suppliers.memoize(() -> splitByBreaks(docs))::get; + /** See {@link #splitsBreaks()}; computed when first asked for, once the docs are all in. */ + @Nullable + private SplitsBreaks memoizedSplitsBreaks; - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedMaxDepth = Suppliers.memoize(() -> computeMaxDepth(docs))::get; + /** See {@link #getMaxDepth()}; -1 until it is computed, when first asked for, once the docs are all in. */ + private int memoizedMaxDepth = -1; /** See {@link #hasCommentByFirstWord()}; computed when first asked for, once the docs are all in. */ @Nullable @@ -144,7 +143,7 @@ public State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State st "one line, comments laid out", state, explorationNode -> tryToLayOutLevelOnOneLine( - commentsHelper, maxWidth, state, memoizedSplitsBreaks.get(), explorationNode)) + commentsHelper, maxWidth, state, splitsBreaks(), explorationNode)) .markAccepted(); } else { newState = new BreakImpl(commentsHelper, maxWidth, state, childLevel).apply(getBreakBehaviour()); @@ -152,6 +151,14 @@ public State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State st return childLevel.finishLevel(state.updateAfterLevel(newState)); } + /** The docs of this level split at its breaks. */ + private SplitsBreaks splitsBreaks() { + if (memoizedSplitsBreaks == null) { + memoizedSplitsBreaks = splitByBreaks(docs); + } + return memoizedSplitsBreaks; + } + /** Whether this level or a level in it holds a comment that the layout counts by its first word only. */ private boolean hasCommentByFirstWord() { if (hasCommentByFirstWord == null) { @@ -397,8 +404,8 @@ private Optional tryInlinePrefixOntoCurrentLine( if (keepIndent) { newState = newState.withIndentIncrementedBy(getPlusIndent()); } - return Optional.of(tryToLayOutLevelOnOneLine( - commentsHelper, maxWidth, newState, memoizedSplitsBreaks.get(), explorationNode)); + return Optional.of( + tryToLayOutLevelOnOneLine(commentsHelper, maxWidth, newState, splitsBreaks(), explorationNode)); } private Optional tryBreakLastLevel( @@ -679,7 +686,7 @@ private static SplitsBreaks splitByBreaks(List docs) { /** Compute breaks for a {@link Level} that spans multiple lines. */ private State computeBroken( CommentsHelper commentsHelper, int maxWidth, State state, Obs.ExplorationNode explorationNode) { - SplitsBreaks splitsBreaks = memoizedSplitsBreaks.get(); + SplitsBreaks splitsBreaks = splitsBreaks(); if (!splitsBreaks.breaks().isEmpty()) { state = state.withBrokenLevel(); @@ -752,7 +759,7 @@ public void write(State state, Output output) { } private void writeFilled(State state, Output output) { - SplitsBreaks splitsBreaks = memoizedSplitsBreaks.get(); + SplitsBreaks splitsBreaks = splitsBreaks(); // Handle first split. for (Doc doc : splitsBreaks.splits().get(0)) { doc.write(state, output); @@ -811,7 +818,10 @@ public String representation(State state) { * Get the approximation of the maximum depth of nested levels in this level tree (memoized). */ private int getMaxDepth() { - return memoizedMaxDepth.get(); + if (memoizedMaxDepth == -1) { + memoizedMaxDepth = computeMaxDepth(docs); + } + return memoizedMaxDepth; } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java index 31fcf769f..8b08fc903 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java @@ -18,13 +18,11 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.Range; -import com.google.errorprone.annotations.Immutable; import com.palantir.javaformat.CommentsHelper; import com.palantir.javaformat.Op; import com.palantir.javaformat.Output; /** A Leaf node in a {@link Doc} for a non-breaking space. */ -@Immutable public final class NonBreakingSpace extends Doc implements Op { private NonBreakingSpace() {}