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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -521,13 +522,32 @@ private static int getI(Input.Token token) {

public record OpsOutput(List<Op> 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<K, V> extends ForwardingListMultimap<K, V> {
private final ArrayListMultimap<K, V> delegate = ArrayListMultimap.create();

@Override
protected ListMultimap<K, V> delegate() {
return delegate;
}

@Override
public List<V> 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<Integer, Op> tokOps = ArrayListMultimap.create();
var tokOps = new SparseListMultimap<Integer, Op>();
// The room after a string literal for the NON-NLS markers written on its line, see Comment.makeNonNlsMarkers.
var reservations = ArrayListMultimap.<Integer, Op>create();
var reservations = new SparseListMultimap<Integer, Op>();
var tokenOps = new HashMap<Input.Token, Integer>();
Map<Integer, Input.Token> tokenByIndex = null;
int opsN = ops.size();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down
30 changes: 20 additions & 10 deletions open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@

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;
import com.palantir.javaformat.Input;
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
Expand All @@ -37,22 +37,26 @@ public abstract class Doc extends HasUniqueId {
static final Range<Integer> EMPTY_RANGE = Range.closedOpen(-1, -1);
static final DiscreteDomain<Integer> INTEGERS = DiscreteDomain.integers();

@SuppressWarnings("Immutable") // Effectively immutable
private final ImmutableSupplier<Float> 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<String> memoizedFlat = Suppliers.memoize(this::computeFlat)::get;
@Nullable
private String memoizedFlat;

@SuppressWarnings("Immutable") // Effectively immutable
private final ImmutableSupplier<Range<Integer>> memoizedRange = Suppliers.memoize(this::computeRange)::get;
@Nullable
private Range<Integer> memoizedRange;

/**
* Return the width of a {@code Doc}, or {@code Float.POSITIVE_INFINITY} if it must be broken.
*
* @return the width
*/
final float getWidth() {
return memoizedWidth.get();
if (Float.isNaN(memoizedWidth)) {
memoizedWidth = computeWidth();
}
return memoizedWidth;
}

/**
Expand All @@ -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<Integer> range() {
return memoizedRange.get();
if (memoizedRange == null) {
memoizedRange = computeRange();
}
return memoizedRange;
}

/**
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -60,12 +59,12 @@ public final class Level extends Doc {

private final List<Doc> docs = new ArrayList<>(); // The elements of the level.

@SuppressWarnings("Immutable") // Effectively immutable
private final ImmutableSupplier<SplitsBreaks> 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<Integer> 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
Expand Down Expand Up @@ -144,14 +143,22 @@ 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());
}
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) {
Expand Down Expand Up @@ -397,8 +404,8 @@ private Optional<State> 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<State> tryBreakLastLevel(
Expand Down Expand Up @@ -679,7 +686,7 @@ private static SplitsBreaks splitByBreaks(List<Doc> 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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}

Expand Down
Loading