Skip to content

Commit d600848

Browse files
committed
Optimize pretty printing performance
swift-format#883 fixed outputting incorrect line numbers, but introduced a performance regression. swift-format#901 improved this back to around the original, but had to be reverted as it introduced a an issue due to counting codepoints rather than characters. Introduce a similar optimization again, but only for the first portion of the string (prior to the last newline). Fixes swift-format#894 again.
1 parent e82cdd7 commit d600848

File tree

2 files changed

+49
-12
lines changed

2 files changed

+49
-12
lines changed

Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift

+15-12
Original file line numberDiff line numberDiff line change
@@ -119,18 +119,21 @@ struct PrettyPrintBuffer {
119119
consecutiveNewlineCount = 0
120120
pendingSpaces = 0
121121

122-
// In case of comments, we may get a multi-line string.
123-
// To account for that case, we need to correct the lineNumber count.
124-
// The new column is only the position within the last line.
125-
let lines = text.split(separator: "\n")
126-
lineNumber += lines.count - 1
127-
if lines.count > 1 {
128-
// in case we have inserted new lines, we need to reset the column
129-
column = lines.last?.count ?? 0
130-
} else {
131-
// in case it is an end of line comment or a single line comment,
132-
// we just add to the current column
133-
column += lines.last?.count ?? 0
122+
guard let lastNewlineIndex = text.lastIndex(of: "\n") else {
123+
// In case there's no newline, the string itself is the only line
124+
column += text.count
125+
return
126+
}
127+
128+
let lastLine = text[lastNewlineIndex...]
129+
column += lastLine.count
130+
131+
// Now count the rest of the lines in a possible multi-line string. We are only interested in '\n' so we can use
132+
// the UTF8 view and skip grapheme clustering entirely.
133+
for element in text[...lastNewlineIndex].utf8 {
134+
if element == UInt8(ascii: "\n") {
135+
lineNumber += 1
136+
}
134137
}
135138
}
136139

Tests/SwiftFormatTests/PrettyPrint/LineNumbersTests.swift

+34
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,38 @@ final class LineNumbersTests: PrettyPrintTestCase {
8181
]
8282
)
8383
}
84+
85+
func testCharacterVsCodepoint() {
86+
let input =
87+
"""
88+
let fo = 1 // 🤥
89+
90+
"""
91+
92+
assertPrettyPrintEqual(
93+
input: input,
94+
expected: input,
95+
linelength: 16,
96+
whitespaceOnly: true,
97+
findings: []
98+
)
99+
}
100+
101+
func testCharacterVsCodepointMultiline() {
102+
let input =
103+
#"""
104+
/// This is a multiline
105+
/// comment that is in 🤥
106+
/// fact perfectly sized
107+
108+
"""#
109+
110+
assertPrettyPrintEqual(
111+
input: input,
112+
expected: input,
113+
linelength: 25,
114+
whitespaceOnly: true,
115+
findings: []
116+
)
117+
}
84118
}

0 commit comments

Comments
 (0)