Skip to content

[Macros] Handle throwing in macro expansions #62571

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 1 commit into from
Dec 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion lib/ASTGen/Sources/ASTGen/Macros.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import SwiftDiagnostics
import SwiftParser
import SwiftSyntax
import _SwiftSyntaxMacros
Expand Down Expand Up @@ -94,6 +95,17 @@ extension String {
}
}

/// Diagnostic message used for thrown errors.
fileprivate struct ThrownErrorDiagnostic: DiagnosticMessage {
let message: String

var severity: DiagnosticSeverity { .error }

var diagnosticID: MessageID {
.init(domain: "SwiftSyntaxMacros", id: "ThrownErrorDiagnostic")
}
}

@_cdecl("swift_ASTGen_evaluateMacro")
@usableFromInline
func evaluateMacro(
Expand Down Expand Up @@ -148,7 +160,19 @@ func evaluateMacro(
return ExprSyntax(parentExpansion)
}

return exprMacro.expansion(of: parentExpansion, in: &context)
do {
return try exprMacro.expansion(of: parentExpansion, in: &context)
} catch {
// Record the error
context.diagnose(
Diagnostic(
node: Syntax(parentExpansion),
message: ThrownErrorDiagnostic(message: String(describing: error))
)
)

return ExprSyntax(parentExpansion)
}
}

// Emit diagnostics accumulated in the context.
Expand Down