Skip to content

Commit 7e4acfa

Browse files
committed
[Macros] Put the insertion location for freestanding macros at the beginning
When building the ASTScope tree, we set the insertion location for the macro expansion just before the end of the macro use. This is the right approach for attached macros, because we need to put the entities after the macro. However, for freestanding macros, which can have trailing closures, this location is a problem, because the scope for the macro expansion ends up inside the scope for the trailing closure. Use the start location of the freestanding macro instead. Fixes rdar://130923190.
1 parent 39f826c commit 7e4acfa

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

lib/AST/ASTScopeCreation.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,11 @@ ASTSourceFileScope::ASTSourceFileScope(SourceFile *SF,
290290
switch (*macroRole) {
291291
case MacroRole::Expression:
292292
case MacroRole::Declaration:
293-
case MacroRole::CodeItem:
293+
case MacroRole::CodeItem: {
294+
parentLoc = SF->getMacroInsertionRange().Start;
295+
break;
296+
}
297+
294298
case MacroRole::Accessor:
295299
case MacroRole::MemberAttribute:
296300
case MacroRole::Conformance:

test/Macros/Inputs/syntax_macro_definitions.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,20 @@ public struct StringifyAndTryMacro: ExpressionMacro {
105105
}
106106
}
107107

108+
public struct TryCallThrowingFuncMacro: ExpressionMacro {
109+
public static func expansion(
110+
of macro: some FreestandingMacroExpansionSyntax,
111+
in context: some MacroExpansionContext
112+
) -> ExprSyntax {
113+
return """
114+
try await {
115+
print("let's throw")
116+
return try await throwingFunc()
117+
}()
118+
"""
119+
}
120+
}
121+
108122
struct SimpleDiagnosticMessage: DiagnosticMessage {
109123
let message: String
110124
let diagnosticID: MessageID

test/Macros/macro_expand.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,16 @@ func testStringifyWithThrows() throws {
308308
_ = #stringifyAndTry(maybeThrowing())
309309
}
310310

311+
func throwingFunc() async throws -> Int { 5 }
312+
313+
@freestanding(expression) macro callThrowingFunc<T>(_ body: () -> T) -> T = #externalMacro(module: "MacroDefinition", type: "TryCallThrowingFuncMacro")
314+
315+
func testThrowingCall() async throws -> Int {
316+
#callThrowingFunc {
317+
[1, 2, 3, 4, 5].map { $0 + 1 }.first!
318+
}
319+
}
320+
311321
func testStringifyWithLocalType() throws {
312322
_ = #stringify({
313323
struct QuailError: Error {}

0 commit comments

Comments
 (0)