-
Notifications
You must be signed in to change notification settings - Fork 441
Added a formatter to pretty print diagnostics #874
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
//===------------ DiagnosticsFormatter.swift - Formatter for diagnostics ----------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2022 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import SwiftSyntax | ||
|
||
public struct DiagnosticsFormatter { | ||
|
||
/// A wrapper struct for a source line and its diagnostics | ||
private struct AnnotatedSourceLine { | ||
var diagnostics: [Diagnostic] | ||
var sourceString: String | ||
} | ||
|
||
/// Number of lines which should be printed before and after the diagnostic message | ||
static let contextSize = 2 | ||
|
||
/// Print given diagnostics for a given syntax tree on the command line | ||
public static func annotatedSource(tree: SourceFileSyntax, diags: [Diagnostic]) -> String { | ||
let slc = SourceLocationConverter(file: "", tree: tree) | ||
|
||
// First, we need to put each line and its diagnostics together | ||
var annotatedSourceLines = [AnnotatedSourceLine]() | ||
|
||
for (sourceLineIndex, sourceLine) in slc.sourceLines.enumerated() { | ||
let diagsForLine = diags.filter { diag in | ||
return diag.location(converter: slc).line == (sourceLineIndex + 1) | ||
} | ||
annotatedSourceLines.append(AnnotatedSourceLine(diagnostics: diagsForLine, sourceString: sourceLine)) | ||
} | ||
|
||
// Only lines with diagnostic messages should be printed, but including some context | ||
let rangesToPrint = annotatedSourceLines.enumerated().compactMap { (lineIndex, sourceLine) -> Range<Int>? in | ||
let lineNumber = lineIndex + 1 | ||
if !sourceLine.diagnostics.isEmpty { | ||
return Range<Int>(uncheckedBounds: (lower: lineNumber - Self.contextSize, upper: lineNumber + Self.contextSize + 1)) | ||
} | ||
return nil | ||
} | ||
|
||
var annotatedSource = "" | ||
|
||
/// Keep track if a line missing char should be printed | ||
var hasLineBeenSkipped = false | ||
|
||
let maxNumberOfDigits = String(annotatedSourceLines.count).count | ||
|
||
for (lineIndex, annotatedLine) in annotatedSourceLines.enumerated() { | ||
let lineNumber = lineIndex + 1 | ||
guard rangesToPrint.contains(where: { range in | ||
range.contains(lineNumber) | ||
}) else { | ||
hasLineBeenSkipped = true | ||
continue | ||
} | ||
|
||
// line numbers should be right aligned | ||
let lineNumberString = String(lineNumber) | ||
let leadingSpaces = String(repeating: " ", count: maxNumberOfDigits - lineNumberString.count) | ||
let linePrefix = "\(leadingSpaces)\(lineNumberString) │ " | ||
|
||
// If necessary, print a line that indicates that there was lines skipped in the source code | ||
if hasLineBeenSkipped && !annotatedSource.isEmpty { | ||
let lineMissingInfoLine = String(repeating: " ", count: maxNumberOfDigits) + " ┆" | ||
annotatedSource.append("\(lineMissingInfoLine)\n") | ||
} | ||
hasLineBeenSkipped = false | ||
|
||
// print the source line | ||
annotatedSource.append("\(linePrefix)\(annotatedLine.sourceString)") | ||
|
||
// If the line did not end with \n (e.g. the last line), append it manually | ||
if annotatedSource.last != "\n" { | ||
annotatedSource.append("\n") | ||
} | ||
|
||
let columnsWithDiagnostics = Set(annotatedLine.diagnostics.map { $0.location(converter: slc).column ?? 0 }) | ||
let diagsPerColumn = Dictionary(grouping: annotatedLine.diagnostics) { diag in | ||
diag.location(converter: slc).column ?? 0 | ||
}.sorted { lhs, rhs in | ||
lhs.key > rhs.key | ||
} | ||
|
||
for (column, diags) in diagsPerColumn { | ||
// compute the string that is shown before each message | ||
var preMessage = String(repeating: " ", count: maxNumberOfDigits) + " ∣" | ||
for c in 0..<column { | ||
if columnsWithDiagnostics.contains(c) { | ||
preMessage.append("│") | ||
} else { | ||
preMessage.append(" ") | ||
} | ||
} | ||
|
||
for diag in diags.dropLast(1) { | ||
annotatedSource.append("\(preMessage)├─ \(diag.message)\n") | ||
} | ||
annotatedSource.append("\(preMessage)╰─ \(diags.last!.message)\n") | ||
|
||
} | ||
} | ||
return annotatedSource | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
Tests/SwiftDiagnosticsTest/DiagnosticsFormatterTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
//===------------------ DiagnosticsFormatterTests.swift -------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2022 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
import XCTest | ||
import SwiftDiagnostics | ||
import SwiftParser | ||
|
||
final class DiagnosticsFormatterTests: XCTestCase { | ||
|
||
func annotate(source: String) throws -> String { | ||
let tree = try Parser.parse(source: source) | ||
let diags = ParseDiagnosticsGenerator.diagnostics(for: tree) | ||
return DiagnosticsFormatter.annotatedSource(tree: tree, diags: diags) | ||
} | ||
|
||
func testSingleDiagnostic() throws { | ||
let source = """ | ||
var foo = bar + | ||
""" | ||
let expectedOutput = """ | ||
1 │ var foo = bar + | ||
∣ ╰─ expected expression in variable | ||
|
||
""" | ||
XCTAssertEqual(expectedOutput, try annotate(source: source)) | ||
} | ||
|
||
func testMultipleDiagnosticsInOneLine() throws { | ||
let source = """ | ||
foo.[].[].[] | ||
""" | ||
let expectedOutput = """ | ||
1 │ foo.[].[].[] | ||
∣ │ │ ╰─ expected identifier in member access | ||
∣ │ ╰─ expected identifier in member access | ||
∣ ╰─ expected identifier in member access | ||
|
||
""" | ||
XCTAssertEqual(expectedOutput, try annotate(source: source)) | ||
} | ||
|
||
func testLineSkipping() throws { | ||
let source = """ | ||
var i = 1 | ||
i = 2 | ||
i = foo( | ||
i = 4 | ||
i = 5 | ||
i = 6 | ||
i = 7 | ||
i = 8 | ||
i = 9 | ||
i = 10 | ||
i = bar( | ||
""" | ||
let expectedOutput = """ | ||
2 │ i = 2 | ||
3 │ i = foo( | ||
4 │ i = 4 | ||
∣ ╰─ expected ')' to end function call | ||
5 │ i = 5 | ||
6 │ i = 6 | ||
┆ | ||
9 │ i = 9 | ||
10 │ i = 10 | ||
11 │ i = bar( | ||
∣ ├─ expected value in function call | ||
∣ ╰─ expected ')' to end function call | ||
|
||
""" | ||
XCTAssertEqual(expectedOutput, try annotate(source: source)) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.