Skip to content

Commit d50165d

Browse files
authored
Fix bug where solver looks at the last piece on line instead of first. (#1367)
The Solver selects states for all pieces in the piece tree to decide how to format. It does so by exploring a tree of incremental solutions where each set of states is a node in the tree and branches are formed by incrementally binding new states. Exploring the full tree is massively slow. A key optimization is that the solver only looks at changing the state of pieces on lines that actually overflow or are invalid. That way pieces on lines that fit and don't need to split are ignored. It goes further: it only looks at the *first* piece on the *first* line that overflows. Any pieces following that one may be affected by how changing the state of the preceding piece changes the formatting, so we ignore those. At least, that's the intent. It turns out there's actually a bug and the solver looks at the *last* piece on the *first* overflowing line. That can lead to subtly different formatting when there are multiple splittable pieces on the same line. In practice, only one extremely weird test was affected. I suspect that if we started running the formatter on larger code samples, we'd find other more obvious mistakes. This fixes that.
1 parent 15f032a commit d50165d

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

lib/src/back_end/code_writer.dart

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,9 @@ class CodeWriter {
147147

148148
// If we haven't found an overflowing line yet, then this line might be one
149149
// so keep track of the pieces we've encountered.
150-
if (!_foundExpandLine && _currentUnsolvedPieces.isNotEmpty) {
150+
if (!_foundExpandLine &&
151+
_nextPieceToExpand == null &&
152+
_currentUnsolvedPieces.isNotEmpty) {
151153
_nextPieceToExpand = _currentUnsolvedPieces.first;
152154
}
153155
}

test/invocation/chain_postfix.stmt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,9 @@ someReceiverObject.method1().method2().method3()
136136
someReceiverObject
137137
.method1()
138138
.method2()
139-
.method3()(
139+
.method3()(argument)(
140140
argument,
141-
)(argument)<T, R>(
141+
)<T, R>(
142142
argument,
143143
argument,
144144
argument,

0 commit comments

Comments
 (0)