Skip to content

Commit 1854942

Browse files
committed
Correctly use UTF-8 indices in highlight calculations
1 parent 2a3fbe2 commit 1854942

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

Sources/SwiftDiagnostics/DiagnosticsFormatter.swift

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,18 +151,19 @@ public struct DiagnosticsFormatter {
151151
}.mergingOverlappingRanges()
152152

153153
// Map the column ranges into index ranges within the source string itself.
154-
let sourceString = annotatedLine.sourceString
154+
let sourceStringUTF8 = annotatedLine.sourceString.utf8
155155
let highlightIndexRanges: [Range<String.Index>] = highlightRanges.map { highlightRange in
156-
let startIndex = sourceString.index(sourceString.startIndex, offsetBy: highlightRange.lowerBound - 1)
157-
let endIndex = sourceString.index(startIndex, offsetBy: highlightRange.count)
156+
let startIndex = sourceStringUTF8.index(sourceStringUTF8.startIndex, offsetBy: highlightRange.lowerBound - 1)
157+
let endIndex = sourceStringUTF8.index(startIndex, offsetBy: highlightRange.count)
158158
return startIndex..<endIndex
159159
}
160160

161161
// Form the annotated string by copying in text from the original source,
162162
// highlighting the column ranges.
163163
var resultSourceString: String = ""
164-
var sourceIndex = sourceString.startIndex
165164
let annotation = ANSIAnnotation.sourceHighlight
165+
let sourceString = annotatedLine.sourceString
166+
var sourceIndex = sourceString.startIndex
166167
for highlightRange in highlightIndexRanges {
167168
// Text before the highlight range
168169
resultSourceString += sourceString[sourceIndex..<highlightRange.lowerBound]

Tests/SwiftDiagnosticsTest/DiagnosticsFormatterTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,11 @@ final class DiagnosticsFormatterTests: XCTestCase {
123123

124124
func testColoringWithHighlights() {
125125
let source = """
126-
for (i = 0; i != 10; i += 1) { }
126+
for (i = 🐮; i != 👩‍👩‍👦‍👦; i += 1) { }
127127
"""
128128

129129
let expectedOutput = """
130-
\u{001B}[0;36m1 │\u{001B}[0;0m for \u{001B}[4;39m(i\u{001B}[0;0m \u{001B}[4;39m= 0; i != 10; i += 1)\u{001B}[0;0m { }
130+
\u{001B}[0;36m1 │\u{001B}[0;0m for \u{001B}[4;39m(i\u{001B}[0;0m \u{001B}[4;39m= 🐮; i != 👩‍👩‍👦‍👦; i += 1)\u{001B}[0;0m { }
131131
\u{001B}[0;36m∣\u{001B}[0;0m │ ╰─ \u{001B}[1;31merror: expected ')' to end tuple pattern\u{001B}[0;0m
132132
\u{001B}[0;36m∣\u{001B}[0;0m ╰─ \u{001B}[1;31merror: C-style for statement has been removed in Swift 3\u{001B}[0;0m
133133

0 commit comments

Comments
 (0)