File: DiagnosticConsoleWriter.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (542 lines) | stat: -rw-r--r-- 23,093 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2021-2024 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import Foundation
import Markdown

/// Writes diagnostic messages to a text output stream.
///
/// By default, this type writes to `stderr`.
public final class DiagnosticConsoleWriter: DiagnosticFormattingConsumer {

    var outputStream: TextOutputStream
    public var formattingOptions: DiagnosticFormattingOptions
    private var diagnosticFormatter: DiagnosticConsoleFormatter
    private var problems: [Problem] = []

    /// Creates a new instance of this class with the provided output stream.
    /// - Parameters:
    ///   - stream: The output stream to which this instance will write.
    ///   - options: The formatting options for the diagnostics.
    ///   - baseURL: A url to be used as a base url when formatting diagnostic source path.
    ///   - highlight: Whether or not to highlight the default diagnostic formatting output.
    public convenience init(
        _ stream: TextOutputStream = LogHandle.standardError,
        formattingOptions options: DiagnosticFormattingOptions = [],
        baseURL: URL? = nil,
        highlight: Bool? = nil
    ) {
        self.init(stream, formattingOptions: options, baseURL: baseURL, highlight: highlight, fileManager: FileManager.default)
    }
    
    package init(
        _ stream: TextOutputStream = LogHandle.standardError,
        formattingOptions options: DiagnosticFormattingOptions = [],
        baseURL: URL? = nil,
        highlight: Bool? = nil,
        fileManager: FileManagerProtocol = FileManager.default
    ) {
        outputStream = stream
        formattingOptions = options
        diagnosticFormatter = Self.makeDiagnosticFormatter(
            options,
            baseURL: baseURL,
            highlight: highlight ?? TerminalHelper.isConnectedToTerminal,
            fileManager: fileManager
        )
    }

    public func receive(_ problems: [Problem]) {
        if formattingOptions.contains(.formatConsoleOutputForTools) {
            // Add a newline after each formatter description, including the last one.
            let text = problems.map { diagnosticFormatter.formattedDescription(for: $0).appending("\n") }.joined()
            outputStream.write(text)
        } else {
            self.problems.append(contentsOf: problems)
        }
    }
    
    public func flush() throws {
        if formattingOptions.contains(.formatConsoleOutputForTools) {
            // For tools, the console writer writes each diagnostic as they are received.
        } else {
            let text = self.diagnosticFormatter.formattedDescription(for: problems)
            outputStream.write(text)
        }
        problems = [] // `flush()` is called more than once. Don't emit the same problems again.
        self.diagnosticFormatter.finalize()
    }
    
    // This is deprecated but still necessary to implement.
    @available(*, deprecated, renamed: "flush()", message: "Use 'flush()' instead. This deprecated API will be removed after 5.11 is released")
    public func finalize() throws {
        try flush()
    }
    
    private static func makeDiagnosticFormatter(
        _ options: DiagnosticFormattingOptions,
        baseURL: URL?,
        highlight: Bool,
        fileManager: FileManagerProtocol
    ) -> DiagnosticConsoleFormatter {
        if options.contains(.formatConsoleOutputForTools) {
            return IDEDiagnosticConsoleFormatter(options: options)
        } else {
            return DefaultDiagnosticConsoleFormatter(baseUrl: baseURL, highlight: highlight, options: options, fileManager: fileManager)
        }
    }
}

// MARK: Formatted descriptions

extension DiagnosticConsoleWriter {
    public static func formattedDescription(for problems: some Sequence<Problem>, options: DiagnosticFormattingOptions = []) -> String {
        formattedDescription(for: problems, options: options, fileManager: FileManager.default)
    }
    package static func formattedDescription(for problems: some Sequence<Problem>, options: DiagnosticFormattingOptions = [], fileManager: FileManagerProtocol) -> String {
        return problems.map { formattedDescription(for: $0, options: options, fileManager: fileManager) }.joined(separator: "\n")
    }
    
    public static func formattedDescription(for problem: Problem, options: DiagnosticFormattingOptions = []) -> String {
        formattedDescription(for: problem, options: options, fileManager: FileManager.default)
    }
    package static func formattedDescription(for problem: Problem, options: DiagnosticFormattingOptions = [], fileManager: FileManagerProtocol = FileManager.default) -> String {
        let diagnosticFormatter = makeDiagnosticFormatter(options, baseURL: nil, highlight: TerminalHelper.isConnectedToTerminal, fileManager: fileManager)
        return diagnosticFormatter.formattedDescription(for: problem)
    }
    
    public static func formattedDescription(for diagnostic: Diagnostic, options: DiagnosticFormattingOptions = []) -> String {
        formattedDescription(for: diagnostic, options: options, fileManager: FileManager.default)
    }
    package static func formattedDescription(for diagnostic: Diagnostic, options: DiagnosticFormattingOptions = [], fileManager: FileManagerProtocol) -> String {
        let diagnosticFormatter = makeDiagnosticFormatter(options, baseURL: nil, highlight: TerminalHelper.isConnectedToTerminal, fileManager: fileManager)
        return diagnosticFormatter.formattedDescription(for: diagnostic)
    }
}

protocol DiagnosticConsoleFormatter {
    var options: DiagnosticFormattingOptions { get set }
    
    func formattedDescription(for problems: some Sequence<Problem>) -> String
    func formattedDescription(for problem: Problem) -> String
    func formattedDescription(for diagnostic: Diagnostic) -> String
    func finalize()
}

extension DiagnosticConsoleFormatter {
    func formattedDescription(for problems: some Sequence<Problem>) -> String {
        return problems.map { formattedDescription(for: $0) }.joined(separator: "\n")
    }
}

// MARK: IDE formatting

struct IDEDiagnosticConsoleFormatter: DiagnosticConsoleFormatter {
    var options: DiagnosticFormattingOptions
    
    func formattedDescription(for problem: Problem) -> String {
        guard let source = problem.diagnostic.source else {
            return formattedDescription(for: problem.diagnostic)
        }
        
        var description = formattedDiagnosticSummary(problem.diagnostic)
        
        // Since solution summaries aren't included in the fixit string we include them in the diagnostic
        // summary so that the solution information isn't dropped.
        
        if !problem.possibleSolutions.isEmpty, description.last?.isPunctuation == false {
            description += "."
        }
        for solution in problem.possibleSolutions {
            description += " \(solution.summary)"
            if description.last?.isPunctuation == false {
                description += "."
            }
        }
        
        // Add explanations and notes
        description += formattedDiagnosticDetails(problem.diagnostic)
        
        // Only one fixit (but multiple related replacements) can be a presented with each diagnostic
        if problem.possibleSolutions.count == 1, let solution = problem.possibleSolutions.first {
            description += solution.replacements.reduce(into: "") { accumulation, replacement in
                let range = replacement.range
                accumulation +=  "\n\(source.path):\(range.lowerBound.line):\(range.lowerBound.column)-\(range.upperBound.line):\(range.upperBound.column): fixit: \(replacement.replacement)"
            }
        }

        return description
    }

    func finalize() {
        // Nothing to do after all diagnostics have been formatted.
    }
    
    public func formattedDescription(for diagnostic: Diagnostic) -> String {
        return formattedDiagnosticSummary(diagnostic) + formattedDiagnosticDetails(diagnostic)
    }
    
    private func formattedDiagnosticSummary(_ diagnostic: Diagnostic) -> String {
        var result = ""

        if let range = diagnostic.range, let url = diagnostic.source {
            result += "\(url.path):\(range.lowerBound.line):\(range.lowerBound.column): "
        } else if let url = diagnostic.source {
            result += "\(url.path): "
        }
        
        result += "\(diagnostic.severity): \(diagnostic.summary)"
        
        return result
    }
    
    private func formattedDiagnosticDetails(_ diagnostic: Diagnostic) -> String {
        var result = ""

        if let explanation = diagnostic.explanation {
            result += "\n\(explanation)"
        }

        if !diagnostic.notes.isEmpty {
            result += "\n"
            result += diagnostic.notes.map { formattedDescription(for: $0) }.joined(separator: "\n")
        }
        
        return result
    }
    
    private func formattedDescription(for note: DiagnosticNote) -> String {
        let location = "\(note.source.path):\(note.range.lowerBound.line):\(note.range.lowerBound.column)"
        return "\(location): note: \(note.message)"
    }
}

// MARK: Default formatting

final class DefaultDiagnosticConsoleFormatter: DiagnosticConsoleFormatter {
    var options: DiagnosticFormattingOptions
    private let baseUrl: URL?
    private let highlight: Bool
    private var sourceLines: [URL: [String]] = [:]
    private var fileManager: FileManagerProtocol

    /// The number of additional lines from the source file that should be displayed both before and after the diagnostic source line.
    private static let contextSize = 2
    
    init(
        baseUrl: URL?,
        highlight: Bool,
        options: DiagnosticFormattingOptions,
        fileManager: FileManagerProtocol
    ) {
        self.baseUrl = baseUrl
        self.highlight = highlight
        self.options = options
        self.fileManager = fileManager
    }
    
    func formattedDescription(for problems: some Sequence<Problem>) -> String {
        let sortedProblems = problems.sorted { lhs, rhs in
            guard let lhsSource = lhs.diagnostic.source,
                  let rhsSource = rhs.diagnostic.source
            else { return lhs.diagnostic.source  == nil }
            
            guard let lhsRange = lhs.diagnostic.range,
                  let rhsRange = rhs.diagnostic.range
            else { return lhsSource.path < rhsSource.path }
            
            if lhsSource.path == rhsSource.path {
                return lhsRange.lowerBound < rhsRange.lowerBound
            } else {
                return lhsSource.path < rhsSource.path
            }
        }

        return sortedProblems.map { formattedDescription(for: $0) }.joined(separator: "\n\n")
    }

    func formattedDescription(for problem: Problem) -> String {
        formattedDiagnosticsSummary(for: problem.diagnostic) +
        formattedDiagnosticDetails(for: problem.diagnostic) +
        formattedDiagnosticSource(for: problem.diagnostic, with: problem.possibleSolutions)
    }

    func formattedDescription(for diagnostic: Diagnostic) -> String {
        formattedDescription(for: Problem(diagnostic: diagnostic))
    }

    func finalize() {
        // Since the `sourceLines` could potentially be big if there were diagnostics in many large files,
        // we remove the cached lines in a clean up step after all diagnostics have been formatted.
        sourceLines = [:]
    }
}

extension DefaultDiagnosticConsoleFormatter {
    private func formattedDiagnosticsSummary(for diagnostic: Diagnostic) -> String {
        let summary =  diagnostic.severity.description + ": " + diagnostic.summary
        if highlight {
            let ansiAnnotation = diagnostic.severity.ansiAnnotation
            return ansiAnnotation.applied(to: summary)
        } else {
            return summary
        }
    }
    
    private func formattedDiagnosticDetails(for diagnostic: Diagnostic) -> String {
        var result = ""
        if let explanation = diagnostic.explanation {
            result.append("\n\(explanation)")
        }
        
        if !diagnostic.notes.isEmpty {
            let formattedNotes = diagnostic.notes
                .map { note in
                    let location = "\(formattedSourcePath(note.source)):\(note.range.lowerBound.line):\(note.range.lowerBound.column)"
                    return "\(location): \(note.message)"
                }
                .joined(separator: "\n")
            result.append("\n\(formattedNotes)")
        }
        
        return result
    }
    
    private func formattedDiagnosticSource(
        for diagnostic: Diagnostic,
        with solutions: [Solution]
    ) -> String {
        var result = ""
        
        guard let url = diagnostic.source
        else { return "" }
        guard let diagnosticRange = diagnostic.range
        else {
            // If the replacement operation involves adding new files,
            // emit the file content as an addition instead of a replacement.
            //
            // Example:
            // --> /path/to/new/file.md
            // Summary
            // suggestion:
            // 0 + Addition file and
            // 1 + multiline file content.
            var addition = ""
            solutions.forEach { solution in
                addition.append("\n" + solution.summary)
                solution.replacements.forEach { replacement in
                    let solutionFragments = replacement.replacement.split(separator: "\n")
                    addition += "\nsuggestion:\n" + solutionFragments.enumerated().map {
                        "\($0.offset) + \($0.element)"
                    }.joined(separator: "\n")
                }
            }
            return "\n--> \(formattedSourcePath(url))\(addition)"
        }
        
        let sourceLines = readSourceLines(url)

        guard sourceLines.indices.contains(diagnosticRange.lowerBound.line - 1), sourceLines.indices.contains(diagnosticRange.upperBound.line - 1) else {
            return "\n--> \(formattedSourcePath(url)):\(max(1, diagnosticRange.lowerBound.line)):\(max(1, diagnosticRange.lowerBound.column))-\(max(1, diagnosticRange.upperBound.line)):\(max(1, diagnosticRange.upperBound.column))"
        }
        
        // A range containing the source lines and some surrounding context.
        let sourceLinesToDisplay = Range(
            uncheckedBounds: (
                lower: diagnosticRange.lowerBound.line - Self.contextSize - 1,
                upper: diagnosticRange.upperBound.line + Self.contextSize
            )
        ).clamped(to: sourceLines.indices)
        let maxLinePrefixWidth = String(sourceLinesToDisplay.upperBound).count
        
        var suggestionsPerLocation = [SourceLocation: [String]]()
        for solution in solutions {
            // Solutions that requires multiple or zero replacements
            // will be shown at the beginning of the diagnostic range. 
            let location: SourceLocation
            if solution.replacements.count == 1 {
                location = solution.replacements.first!.range.lowerBound
            } else {
                location = diagnosticRange.lowerBound
            }

            suggestionsPerLocation[location, default: []].append(solution.summary)
        }

        // Constructs the header for the diagnostic output.
        // This header is aligned with the line prefix and includes the file path and the range of the diagnostic.\
        //
        // Example:
        //   --> /path/to/file.md:1:10-2:20
        result.append("\n\(String(repeating: " ", count: maxLinePrefixWidth))--> ")
        result.append(        "\(formattedSourcePath(url)):\(max(1, diagnosticRange.lowerBound.line)):\(max(1, diagnosticRange.lowerBound.column))-\(max(1, diagnosticRange.upperBound.line)):\(max(1, diagnosticRange.upperBound.column))")

        for (sourceLineIndex, sourceLine) in sourceLines[sourceLinesToDisplay].enumerated() {
            let lineNumber = sourceLineIndex + sourceLinesToDisplay.lowerBound + 1
            let linePrefix = "\(lineNumber)".padding(toLength: maxLinePrefixWidth, withPad: " ", startingAt: 0)

            let highlightedSource = highlightSource(
                sourceLine: sourceLine,
                lineNumber: lineNumber,
                range: diagnosticRange, 
                _diagnostic: diagnostic
            )
            
            let separator: String
            if lineNumber >= diagnosticRange.lowerBound.line && lineNumber <= diagnosticRange.upperBound.line {
                separator = "+"
            } else {
                separator = "|"
            }

            // Adds to the header, a formatted source line containing the line number as prefix and a source line.
            // A source line is contained in the diagnostic range will be highlighted.
            //
            // Example:
            // 9  | A line outside the diagnostic range.
            // 10 + A line inside the diagnostic range.
            result.append("\n\(linePrefix) \(separator) \(highlightedSource)".removingTrailingWhitespace())

            var suggestionsPerColumn = [Int: [String]]()

            for (location, suggestions) in suggestionsPerLocation where location.line == lineNumber {
                suggestionsPerColumn[location.column] = suggestions
            }

            let sortedColumns = suggestionsPerColumn.keys.sorted(by: >)

            guard let firstColumn = sortedColumns.first else { continue }

            let suggestionLinePrefix = String(repeating: " ", count: maxLinePrefixWidth) + " |"

            // Constructs a prefix containing vertical separator at each column containing a suggestion.
            // Suggestions are shown on different lines, this allows to visually connect a suggestion shown several lines below
            // with the source code column.
            //
            // Example:
            // 9  | A line outside the diagnostic range.
            // 10 + A line inside the diagnostic range.
            //    |   │    ╰─suggestion: A suggestion.
            //    |   ╰─ suggestion: Another suggestion.
            var longestPrefix = [Character](repeating: " ", count: firstColumn + 1)
            for column in sortedColumns {
                longestPrefix[column] = "│"
            }

            for columnNumber in sortedColumns {
                let columnSuggestions = suggestionsPerColumn[columnNumber, default: []]
                let prefix = suggestionLinePrefix + String(longestPrefix.prefix(columnNumber))

                for (index, suggestion) in columnSuggestions.enumerated() {
                    // Highlight suggestion and make sure it's displayed on a single line.
                    let singleLineSuggestion = suggestion.split(separator: "\n", omittingEmptySubsequences: true).joined(separator: "")
                    let highlightedSuggestion = highlightSuggestion("suggestion: \(singleLineSuggestion)")

                    if index == columnSuggestions.count - 1 {
                        result.append("\n\(prefix)╰─\(highlightedSuggestion)")
                    } else {
                        result.append("\n\(prefix)├─\(highlightedSuggestion)")
                    }
                }
            }
        }
        
        return result
    }
    
    private func highlightSuggestion(
        _ suggestion: String
    ) -> String {
        guard highlight
        else { return suggestion }
        
        let suggestionAnsiAnnotation = ANSIAnnotation.sourceSuggestionHighlight
        return suggestionAnsiAnnotation.applied(to: suggestion)
    }

    private func highlightSource(
        sourceLine: String,
        lineNumber: Int,
        range: SourceRange,
        _diagnostic: Diagnostic // used in a debug assertion to identify diagnostics with incorrect source ranges
    ) -> String {
        guard highlight,
              lineNumber >= range.lowerBound.line && lineNumber <= range.upperBound.line,
              !sourceLine.isEmpty
        else {
            return sourceLine
        }
        
        guard range.lowerBound.line == range.upperBound.line else {
            // When highlighting multiple lines, highlight the full line
            return ANSIAnnotation.sourceHighlight.applied(to: sourceLine)
        }

        let sourceLineUTF8 = sourceLine.utf8
        
        let highlightStart = max(0, range.lowerBound.column - 1)
        let highlightEnd = range.upperBound.column - 1
        
        assert(highlightStart <= sourceLineUTF8.count, {
            """
            Received diagnostic with incorrect source range; (\(range.lowerBound.column) ..< \(range.upperBound.column)) extends beyond the text on line \(lineNumber) (\(sourceLineUTF8.count) characters)
             █\(sourceLine)
             █\(String(repeating: " ", count: range.lowerBound.column))\(String(repeating: "~", count: range.upperBound.column - range.lowerBound.column))
            Use this diagnostic information to reproduce the issue and correct the diagnostic range where it's emitted.
             ID      : \(_diagnostic.identifier)
             SUMMARY : \(_diagnostic.summary)
             SOURCE  : \(_diagnostic.source?.path ?? _diagnostic.range?.source?.path ?? "<nil>")
            """
        }())
        
        guard let before = String(sourceLineUTF8.prefix(highlightStart)),
              let highlighted = String(sourceLineUTF8.dropFirst(highlightStart).prefix(highlightEnd - highlightStart)),
              let after = String(sourceLineUTF8.dropFirst(highlightEnd))
        else {
            return sourceLine
        }
        
        return "\(before)\(ANSIAnnotation.sourceHighlight.applied(to: highlighted))\(after)"
    }

    private func readSourceLines(_ url: URL) -> [String] {
        if let lines = sourceLines[url] {
            return lines
        }

        // TODO: Add support for also getting the source lines from the symbol graph files.
        guard let data = fileManager.contents(atPath: url.path),
              let content = String(data: data, encoding: .utf8)
        else { 
            return []
        }
        
        let lines = content.splitByNewlines
        sourceLines[url] = lines
        return lines
    }

    private func formattedSourcePath(_ url: URL) -> String {
        baseUrl.flatMap { url.relative(to: $0) }.map(\.path) ?? url.path
    }
}

private extension DiagnosticSeverity {
    var ansiAnnotation: ANSIAnnotation {
        switch self {
        case .error:
            return .init(color: .red, trait: .bold)
        case .warning:
            return .init(color: .yellow, trait: .bold)
        case .information, .hint:
            return .init(color: .default, trait: .bold)
        }
    }
}