Skip to content

Commit 36da4fc

Browse files
cushongoogle-java-format Team
authored andcommitted
Add a layout solver to google-java-format based on Wadler's prettier printer.
Replace the Oppen-style `Doc.Level` break computation with an immutable document model and a separate solver, based on Philip Wadler's "A prettier printer" (https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf). A `layout.Doc` is built from `text`, `line` and `group`, and `layout.LayoutSolver` lays it out greedily in a single pass: each group is printed flat if it fits (Wadler's `group x = flatten x <|> x`), and otherwise its breaks are taken. Fill breaks correspond to Wadler's `fill`. `layout.LayoutBuilder` bridges the existing visitor to the new model. It provides the same operations as `OpsBuilder`, so `JavaInputAstVisitor` is unchanged apart from the builder type. The builder applies the same rules as the existing engine, for example the group-local fit test and attaching trailing text to the group of the most recent break. All existing formatting is preserved, and every integration test golden is unchanged. PiperOrigin-RevId: 986705449
1 parent 1959806 commit 36da4fc

14 files changed

Lines changed: 1633 additions & 19 deletions

File tree

‎core/src/main/java/com/google/googlejavaformat/Doc.java‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ public enum RealOrImaginary {
365365
REAL,
366366
IMAGINARY;
367367

368-
boolean isReal() {
368+
public boolean isReal() {
369369
return this == REAL;
370370
}
371371
}
@@ -395,12 +395,12 @@ private Token(
395395
*
396396
* @return the extra indent
397397
*/
398-
Indent getPlusIndentCommentsBefore() {
398+
public Indent getPlusIndentCommentsBefore() {
399399
return plusIndentCommentsBefore;
400400
}
401401

402402
/** Force a line break and indent trailing javadoc or block comments. */
403-
Optional<Indent> breakAndIndentTrailingComment() {
403+
public Optional<Indent> breakAndIndentTrailingComment() {
404404
return breakAndIndentTrailingComment;
405405
}
406406

@@ -427,7 +427,7 @@ static Op make(
427427
*
428428
* @return the {@link Input.Token}
429429
*/
430-
Input.Token getToken() {
430+
public Input.Token getToken() {
431431
return token;
432432
}
433433

@@ -436,7 +436,7 @@ Input.Token getToken() {
436436
*
437437
* @return whether the @code Token} is good
438438
*/
439-
RealOrImaginary realOrImaginary() {
439+
public RealOrImaginary realOrImaginary() {
440440
return realOrImaginary;
441441
}
442442

@@ -483,7 +483,7 @@ public String toString() {
483483
}
484484

485485
/** A Leaf node in a {@link Doc} for a non-breaking space. */
486-
static final class Space extends Doc implements Op {
486+
public static final class Space extends Doc implements Op {
487487
private static final Space SPACE = new Space();
488488

489489
private Space() {}
@@ -600,6 +600,22 @@ boolean isForced() {
600600
return fillMode == FillMode.FORCED;
601601
}
602602

603+
public FillMode fillMode() {
604+
return fillMode;
605+
}
606+
607+
public String flat() {
608+
return flat;
609+
}
610+
611+
public Indent plusIndent() {
612+
return plusIndent;
613+
}
614+
615+
public Optional<BreakTag> optTag() {
616+
return optTag;
617+
}
618+
603619
@Override
604620
public void add(DocBuilder builder) {
605621
builder.breakDoc(this);

‎core/src/main/java/com/google/googlejavaformat/Indent.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
*/
2525
public abstract class Indent {
2626

27-
abstract int eval();
27+
public abstract int eval();
2828

2929
/** A constant function, returning a constant indent. */
3030
public static final class Const extends Indent {
@@ -41,7 +41,7 @@ public static Const make(int n, int indentMultiplier) {
4141
}
4242

4343
@Override
44-
int eval() {
44+
public int eval() {
4545
return n;
4646
}
4747

@@ -68,7 +68,7 @@ public static If make(BreakTag condition, Indent thenIndent, Indent elseIndent)
6868
}
6969

7070
@Override
71-
int eval() {
71+
public int eval() {
7272
return (condition.wasBreakTaken() ? thenIndent : elseIndent).eval();
7373
}
7474

‎core/src/main/java/com/google/googlejavaformat/Newlines.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,21 @@ public static int firstBreak(String input) {
3535
return it.hasNext() ? it.next() : -1;
3636
}
3737

38+
/**
39+
* Returns the offset of the start of the last line in the input, or {@code 0} if the input
40+
* contains no line breaks. Unlike iterating over {@link #lineOffsetIterator}, this only scans the
41+
* last line.
42+
*/
43+
public static int lastLineStart(String input) {
44+
for (int i = input.length() - 1; i >= 0; i--) {
45+
char c = input.charAt(i);
46+
if (c == '\n' || c == '\r') {
47+
return i + 1;
48+
}
49+
}
50+
return 0;
51+
}
52+
3853
private static final ImmutableSet<String> BREAKS = ImmutableSet.of("\r\n", "\n", "\r");
3954

4055
/** Returns true if the entire input string is a recognized line break. */

‎core/src/main/java/com/google/googlejavaformat/OpenOp.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ public void add(DocBuilder builder) {
4444
builder.open(plusIndent);
4545
}
4646

47+
public Indent plusIndent() {
48+
return plusIndent;
49+
}
50+
4751
@Override
4852
public String toString() {
4953
return MoreObjects.toStringHelper(this).add("plusIndent", plusIndent).toString();

‎core/src/main/java/com/google/googlejavaformat/java/Formatter.java‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
import com.google.errorprone.annotations.Immutable;
2626
import com.google.googlejavaformat.CommentsHelper;
2727
import com.google.googlejavaformat.Doc;
28-
import com.google.googlejavaformat.DocBuilder;
2928
import com.google.googlejavaformat.FormattingError;
3029
import com.google.googlejavaformat.Newlines;
3130
import com.google.googlejavaformat.Op;
32-
import com.google.googlejavaformat.OpsBuilder;
31+
import com.google.googlejavaformat.layout.LayoutBuilder;
32+
import com.google.googlejavaformat.layout.LayoutSolver;
3333
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
3434
import com.sun.tools.javac.util.Context;
3535
import java.io.IOException;
@@ -113,22 +113,21 @@ static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatt
113113
if (!errorDiagnostics.isEmpty()) {
114114
throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
115115
}
116-
OpsBuilder builder = new OpsBuilder(javaInput, javaOutput);
116+
LayoutBuilder builder = new LayoutBuilder(javaInput, javaOutput);
117117
ImmutableSet.Builder<Integer> markdownJavadocPositions = ImmutableSet.builder();
118118
// Output the compilation unit.
119119
JavaInputAstVisitor visitor =
120120
new JavaInputAstVisitor(builder, options.indentationMultiplier(), markdownJavadocPositions);
121121
visitor.scan(unit, null);
122122
builder.sync(javaInput.getText().length());
123123
builder.drain();
124-
Doc doc = new DocBuilder().withOps(builder.build()).build();
124+
var doc = builder.build();
125125
CommentsHelper commentsHelper =
126126
new JavaCommentsHelper(
127127
Newlines.guessLineSeparator(javaInput.getText()),
128128
options,
129129
markdownJavadocPositions.build());
130-
doc.computeBreaks(commentsHelper, options.maxLineLength(), new Doc.State(+0, 0));
131-
doc.write(javaOutput);
130+
LayoutSolver.format(doc, options.maxLineLength(), javaOutput, commentsHelper);
132131
javaOutput.flush();
133132
}
134133

‎core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,11 @@
7878
import com.google.googlejavaformat.Newlines;
7979
import com.google.googlejavaformat.Op;
8080
import com.google.googlejavaformat.OpenOp;
81-
import com.google.googlejavaformat.OpsBuilder;
8281
import com.google.googlejavaformat.OpsBuilder.BlankLineWanted;
8382
import com.google.googlejavaformat.Output.BreakTag;
8483
import com.google.googlejavaformat.java.DimensionHelpers.SortedDims;
8584
import com.google.googlejavaformat.java.DimensionHelpers.TypeWithDims;
85+
import com.google.googlejavaformat.layout.LayoutBuilder;
8686
import com.sun.source.tree.AnnotatedTypeTree;
8787
import com.sun.source.tree.AnnotationTree;
8888
import com.sun.source.tree.ArrayAccessTree;
@@ -272,7 +272,7 @@ private static ImmutableSetMultimap<String, String> typeAnnotations() {
272272
return result.build();
273273
}
274274

275-
private final OpsBuilder builder;
275+
private final LayoutBuilder builder;
276276
private final ImmutableSet.Builder<Integer> markdownJavadocPositions;
277277

278278
private static final Indent.Const ZERO = Indent.Const.ZERO;
@@ -308,10 +308,10 @@ private static final ImmutableList<Op> forceBreakList(Optional<BreakTag> breakTa
308308
/**
309309
* The {@code Visitor} constructor.
310310
*
311-
* @param builder the {@link OpsBuilder}
311+
* @param builder the {@link LayoutBuilder}
312312
*/
313313
JavaInputAstVisitor(
314-
OpsBuilder builder,
314+
LayoutBuilder builder,
315315
int indentMultiplier,
316316
ImmutableSet.Builder<Integer> markdownJavadocPositions) {
317317
this.builder = builder;

0 commit comments

Comments
 (0)