Skip to content

Commit de22201

Browse files
authored
Merge pull request #1085 from rxwei/macro-plugin-diagnostics
[Macros] Plumb diagnostics through the plugin interface
2 parents f1cea7d + 6c95d02 commit de22201

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

Sources/_SwiftSyntaxMacros/ExpressionMacro.swift

Lines changed: 27 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: self = .note
34+
case .warning: self = .warning
35+
case .error: self = .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,25 @@ extension ExpressionMacro {
6679
// Evaluate the macro.
6780
let evalResult = apply(mee, in: context)
6881

82+
let rawDiags = UnsafeMutablePointer<_Diagnostic>.allocate(
83+
capacity: evalResult.diagnostics.count)
84+
for (i, diag) in evalResult.diagnostics.enumerated() {
85+
rawDiags.advanced(by: i).initialize(to: _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: UnsafePointer?(rawDiags),
100+
diagnosticCount: evalResult.diagnostics.count)
76101
}
77102
}
78103
}

0 commit comments

Comments
 (0)