Skip to content

Commit 5a36ad4

Browse files
authored
Merge pull request #1142 from DougGregor/throwing-macro-expansion
2 parents 51d06bf + 9cd4529 commit 5a36ad4

File tree

2 files changed

+24
-17
lines changed

2 files changed

+24
-17
lines changed

Sources/_SwiftSyntaxMacros/ExpressionMacro.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@ public protocol ExpressionMacro: Macro {
2121
static func expansion(
2222
of node: MacroExpansionExprSyntax,
2323
in context: inout MacroExpansionContext
24-
) -> ExprSyntax
24+
) throws -> ExprSyntax
2525
}

Sources/_SwiftSyntaxMacros/Syntax+MacroEvaluation.swift

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,18 @@
1313
import SwiftDiagnostics
1414
import SwiftSyntax
1515

16-
extension MacroExpansionExprSyntax {
17-
private func disconnectedCopy() -> MacroExpansionExprSyntax {
18-
MacroExpansionExprSyntax(
19-
unexpectedBeforePoundToken, poundToken: poundToken,
20-
unexpectedBetweenPoundTokenAndMacro, macro: macro,
21-
genericArguments: genericArguments,
22-
unexpectedBetweenGenericArgumentsAndLeftParen, leftParen: leftParen,
23-
unexpectedBetweenLeftParenAndArgumentList, argumentList: argumentList,
24-
unexpectedBetweenArgumentListAndRightParen, rightParen: rightParen,
25-
unexpectedBetweenRightParenAndTrailingClosure,
26-
trailingClosure: trailingClosure,
27-
unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures,
28-
additionalTrailingClosures: additionalTrailingClosures,
29-
unexpectedAfterAdditionalTrailingClosures
30-
)
16+
/// Diagnostic message used for thrown errors.
17+
struct ThrownErrorDiagnostic: DiagnosticMessage {
18+
let message: String
19+
20+
var severity: DiagnosticSeverity { .error }
21+
22+
var diagnosticID: MessageID {
23+
.init(domain: "SwiftSyntaxMacros", id: "ThrownErrorDiagnostic")
3124
}
25+
}
3226

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

4338
// Handle the rewrite.
44-
return exprMacro.expansion(of: disconnectedCopy(), in: &context)
39+
do {
40+
return try exprMacro.expansion(of: detach(), in: &context)
41+
} catch {
42+
// Record the error
43+
context.diagnose(
44+
Diagnostic(
45+
node: Syntax(self),
46+
message: ThrownErrorDiagnostic(message: String(describing: error))
47+
)
48+
)
49+
50+
return ExprSyntax(self)
51+
}
4552
}
4653
}
4754

0 commit comments

Comments
 (0)