Skip to content

Throwing macro expansion #1142

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 2 commits into from
Dec 14, 2022
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Sources/_SwiftSyntaxMacros/ExpressionMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ public protocol ExpressionMacro: Macro {
static func expansion(
of node: MacroExpansionExprSyntax,
in context: inout MacroExpansionContext
) -> ExprSyntax
) throws -> ExprSyntax
}
39 changes: 23 additions & 16 deletions Sources/_SwiftSyntaxMacros/Syntax+MacroEvaluation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,18 @@
import SwiftDiagnostics
import SwiftSyntax

extension MacroExpansionExprSyntax {
private func disconnectedCopy() -> MacroExpansionExprSyntax {
MacroExpansionExprSyntax(
unexpectedBeforePoundToken, poundToken: poundToken,
unexpectedBetweenPoundTokenAndMacro, macro: macro,
genericArguments: genericArguments,
unexpectedBetweenGenericArgumentsAndLeftParen, leftParen: leftParen,
unexpectedBetweenLeftParenAndArgumentList, argumentList: argumentList,
unexpectedBetweenArgumentListAndRightParen, rightParen: rightParen,
unexpectedBetweenRightParenAndTrailingClosure,
trailingClosure: trailingClosure,
unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures,
additionalTrailingClosures: additionalTrailingClosures,
unexpectedAfterAdditionalTrailingClosures
)
/// Diagnostic message used for thrown errors.
struct ThrownErrorDiagnostic: DiagnosticMessage {
let message: String

var severity: DiagnosticSeverity { .error }

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

extension MacroExpansionExprSyntax {
/// Evaluate the given macro for this syntax node, producing the expanded
/// result and (possibly) some diagnostics.
func evaluateMacro(
Expand All @@ -41,7 +36,19 @@ extension MacroExpansionExprSyntax {
}

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

return ExprSyntax(self)
}
}
}

Expand Down