Skip to content

Commit 1cedcd2

Browse files
committed
[Macros] Plumb diagnostics through the plugin interface
1 parent 9474729 commit 1cedcd2

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

Sources/_SwiftSyntaxMacros/ExpressionMacro.swift

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import SwiftSyntax
1414
import SwiftParser
15+
import SwiftDiagnostics
1516
#if canImport(_CompilerPluginSupport)
1617
import _CompilerPluginSupport
1718
#endif
@@ -26,6 +27,16 @@ public protocol ExpressionMacro: Macro {
2627
}
2728

2829
#if canImport(_CompilerPluginSupport)
30+
extension _CompilerPluginSupport._DiagnosticSeverity {
31+
fileprivate init(_ other: SwiftDiagnostics.DiagnosticSeverity) {
32+
switch other {
33+
case .note: return .note
34+
case .warning: return .warning
35+
case .error: return .error
36+
}
37+
}
38+
}
39+
2940
extension ExpressionMacro {
3041
public static func _kind() -> _CompilerPluginKind {
3142
.expressionMacro
@@ -40,7 +51,9 @@ extension ExpressionMacro {
4051
sourceFileTextCount: Int,
4152
localSourceText: UnsafePointer<UInt8>,
4253
localSourceTextCount: Int
43-
) -> (UnsafePointer<UInt8>?, count: Int) {
54+
) -> (code: UnsafePointer<UInt8>?, codeLength: Int,
55+
diagnostics: UnsafePointer<_Diagnostic>?,
56+
diagnosticCount: Int) {
4457
let targetModuleNameBuffer = UnsafeBufferPointer(
4558
start: filePath, count: targetModuleNameCount)
4659
let targetModuleName = String(
@@ -66,13 +79,24 @@ extension ExpressionMacro {
6679
// Evaluate the macro.
6780
let evalResult = apply(mee, in: context)
6881

82+
let rawDiags = UnsafeMutableBufferPointer<_Diagnostic>.allocate(
83+
capacity: evalResult.diagnostics.count)
84+
for (i, diag) in evalResult.diagnostics.enumerated() {
85+
rawDiags[i] = _makeDiagnostic(
86+
message: diag.message,
87+
position: diag.position.utf8Offset,
88+
severity: .init(diag.diagMessage.severity))
89+
}
90+
6991
var resultString = "\(evalResult.rewritten)"
7092
return resultString.withUTF8 { buffer in
7193
let result = UnsafeMutableBufferPointer<UInt8>.allocate(
7294
capacity: buffer.count + 1)
7395
_ = result.initialize(from: buffer)
7496
result[buffer.count] = 0
75-
return (UnsafePointer(result.baseAddress), buffer.count)
97+
return (
98+
code: UnsafePointer(result.baseAddress), codeLength: buffer.count,
99+
diagnostics: rawDiags, diagnosticCount: evalResult.diagnostics.count)
76100
}
77101
}
78102
}

0 commit comments

Comments
 (0)