Skip to content

Commit fa54d70

Browse files
committed
[Macros] Handle throwing in macro expansions
1 parent 9cebd69 commit fa54d70

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

lib/ASTGen/Sources/ASTGen/Macros.swift

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import SwiftDiagnostics
12
import SwiftParser
23
import SwiftSyntax
34
import _SwiftSyntaxMacros
@@ -94,6 +95,17 @@ extension String {
9495
}
9596
}
9697

98+
/// Diagnostic message used for thrown errors.
99+
fileprivate struct ThrownErrorDiagnostic: DiagnosticMessage {
100+
let message: String
101+
102+
var severity: DiagnosticSeverity { .error }
103+
104+
var diagnosticID: MessageID {
105+
.init(domain: "SwiftSyntaxMacros", id: "ThrownErrorDiagnostic")
106+
}
107+
}
108+
97109
@_cdecl("swift_ASTGen_evaluateMacro")
98110
@usableFromInline
99111
func evaluateMacro(
@@ -148,7 +160,19 @@ func evaluateMacro(
148160
return ExprSyntax(parentExpansion)
149161
}
150162

151-
return exprMacro.expansion(of: parentExpansion, in: &context)
163+
do {
164+
return try exprMacro.expansion(of: parentExpansion, in: &context)
165+
} catch {
166+
// Record the error
167+
context.diagnose(
168+
Diagnostic(
169+
node: Syntax(parentExpansion),
170+
message: ThrownErrorDiagnostic(message: String(describing: error))
171+
)
172+
)
173+
174+
return ExprSyntax(parentExpansion)
175+
}
152176
}
153177

154178
// Emit diagnostics accumulated in the context.

0 commit comments

Comments
 (0)