File: ANSIDiagnosticDecorator.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 (223 lines) | stat: -rw-r--r-- 7,323 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//

extension DiagnosticDecorator where Self == ANSIDiagnosticDecorator {
  /// - SeeAlso: ``ANSIDiagnosticDecorator``
  static var ANSI: Self {
    Self()
  }
}

/// An implementation of the `DiagnosticDecorator` protocol that enhances various diagnostic elements—including messages,
/// buffer outlines, and code highlights—by applying severity-based prefixes and ANSI color codes.
///
/// This decorator uses ANSI codes—control characters specialized for text formatting in terminals—to provide visual cues.
@_spi(Testing) public struct ANSIDiagnosticDecorator: DiagnosticDecorator {

  @_spi(Testing) public init() {}

  /// Decorates a diagnostic message by appending a severity-based prefix and applying ANSI color codes.
  ///
  /// - Parameters:
  ///   - message: The diagnostic message that needs to be decorated.
  ///   - severity: The severity level associated with the diagnostic message.
  ///
  /// - Returns: A string that combines the severity-specific prefix and the original diagnostic message, with ANSI colorization.
  ///
  /// ## Example
  ///
  /// ```swift
  /// let decorator = ANSIDiagnosticDecorator()
  /// let decoratedMessage = decorator.decorateMessage("File not found", basedOnSeverity: .error)
  /// // Output would be: "error: File not found"
  /// ```
  /// In this example, the "error: " prefix is colorized, likely appearing in red, while the message retains its default text color.
  ///
  /// For a similar colorized output in the console, you can use `printf` in Bash:
  /// ```bash
  /// printf "\e[1;31merror: \e[1;39mFile not found\e[0;0m\n"
  /// ```
  @_spi(Testing) public func decorateMessage(
    _ message: String,
    basedOnSeverity severity: DiagnosticSeverity
  ) -> String {
    let severityText: String
    let severityAnnotation: ANSIAnnotation

    switch severity {
    case .error:
      severityText = "error"
      severityAnnotation = .errorText

    case .warning:
      severityText = "warning"
      severityAnnotation = .warningText

    case .note:
      severityText = "note"
      severityAnnotation = .noteText

    case .remark:
      severityText = "remark"
      severityAnnotation = .remarkText
    }

    let prefix = colorizeIfNotEmpty(
      "\(severityText): ",
      usingAnnotation: severityAnnotation,
      resetAfterApplication: false
    )

    return prefix + colorizeIfNotEmpty(message, usingAnnotation: .diagnosticText)
  }

  /// Decorates a source code buffer outline using ANSI cyan color codes.
  ///
  /// - Parameter bufferOutline: The string representation of the source code buffer outline.
  ///
  /// - Returns: A string featuring ANSI cyan color codes applied to the source code buffer outline.
  @_spi(Testing) public func decorateBufferOutline(_ bufferOutline: String) -> String {
    colorizeIfNotEmpty(bufferOutline, usingAnnotation: .bufferOutline)
  }

  /// Emphasizes a specific text segment within a source code snippet using ANSI color codes.
  ///
  /// - Parameter highlight: The text segment within the source code snippet that should be emphasized.
  ///
  /// - Returns: A tuple containing:
  ///   - `highlightedSourceCode`: The underlined version of the original source code snippet.
  ///   - `additionalHighlightedLine`: Always nil.
  ///
  /// ## Example
  ///
  /// ```swift
  /// let decorator = ANSIDiagnosticDecorator()
  /// let decoratedHighlight = decorator.decorateHighlight("let x = 10")
  /// // Output would be: ["\u{1B}[4;39mlet x = 10\u{1B}[0;0m"]
  /// ```
  ///
  /// To reproduce a similar colorized output manually in the console, you can use `printf` in Bash:
  /// ```bash
  /// printf "\e[4;39mlet x = 10\e[0;0m\n"
  /// ```
  @_spi(Testing) public func decorateHighlight(_ highlight: String) -> (
    highlightedSourceCode: String, additionalHighlightedLine: String?
  ) {
    (
      highlightedSourceCode: colorizeIfNotEmpty(highlight, usingAnnotation: .sourceHighlight),
      additionalHighlightedLine: nil
    )
  }

  /// Applies ANSI annotation to a given text segment, if the text is not empty.
  ///
  /// - Parameters:
  ///   - text: The text segment to which the annotation should be applied.
  ///   - annotation: The ANSI annotation to apply.
  ///   - resetAfter: A flag indicating whether to reset ANSI settings after applying them. Defaults to true.
  ///
  /// - Returns: A potentially colorized version of the input text.
  private func colorizeIfNotEmpty(
    _ text: String,
    usingAnnotation annotation: ANSIAnnotation,
    resetAfterApplication resetAfter: Bool = true
  ) -> String {
    if text.isEmpty {
      return text
    } else {
      return annotation.applied(to: text, resetAfter: resetAfter)
    }
  }
}

/// Defines text attributes to be applied to console output.
private struct ANSIAnnotation {
  /// Represents ANSI color codes.
  enum Color: UInt8 {
    case normal = 0
    case black = 30
    case red = 31
    case green = 32
    case yellow = 33
    case blue = 34
    case magenta = 35
    case cyan = 36
    case white = 37
    case `default` = 39
  }

  /// Represents ANSI text traits.
  enum Trait: UInt8 {
    case normal = 0
    case bold = 1
    case underline = 4
  }

  /// The ANSI color to be used.
  let color: Color

  /// The ANSI text trait to be used.
  let trait: Trait

  /// Returns ANSI code as a string, including both trait and color.
  var code: String {
    "\u{001B}[\(trait.rawValue);\(color.rawValue)m"
  }

  /// Applies the ANSI code to a message string. Optionally resets the code after the message.
  func applied(to message: String, resetAfter: Bool = true) -> String {
    guard resetAfter else {
      return "\(code)\(message)"
    }
    return "\(code)\(message)\(ANSIAnnotation.normal.code)"
  }

  /// The default 'normal' ANSIAnnotation used to reset styles.
  static var normal: Self {
    Self(color: .normal, trait: .normal)
  }

  /// Annotation used for the outline and line numbers of a buffer.
  static var bufferOutline: Self {
    Self(color: .cyan, trait: .normal)
  }

  /// Annotation used for highlighting source text.
  static var sourceHighlight: Self {
    Self(color: .default, trait: .underline)
  }

  /// Annotation used for making text bold, commonly used in diagnostic messages.
  static var diagnosticText: Self {
    Self(color: .default, trait: .bold)
  }

  /// Annotation used for error text.
  static var errorText: Self {
    Self(color: .red, trait: .bold)
  }

  /// Annotation used for warning text.
  static var warningText: Self {
    Self(color: .yellow, trait: .bold)
  }

  /// Annotation used for note text.
  static var noteText: Self {
    Self(color: .default, trait: .bold)
  }

  /// Annotation used for remarks or less critical text.
  static var remarkText: Self {
    Self(color: .blue, trait: .bold)
  }
}