Skip to content

[Macros] Put the insertion location for freestanding macros at the beginning #74925

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
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
6 changes: 5 additions & 1 deletion lib/AST/ASTScopeCreation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,11 @@ ASTSourceFileScope::ASTSourceFileScope(SourceFile *SF,
switch (*macroRole) {
case MacroRole::Expression:
case MacroRole::Declaration:
case MacroRole::CodeItem:
case MacroRole::CodeItem: {
parentLoc = SF->getMacroInsertionRange().Start;
break;
}

case MacroRole::Accessor:
case MacroRole::MemberAttribute:
case MacroRole::Conformance:
Expand Down
14 changes: 14 additions & 0 deletions test/Macros/Inputs/syntax_macro_definitions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@ public struct StringifyAndTryMacro: ExpressionMacro {
}
}

public struct TryCallThrowingFuncMacro: ExpressionMacro {
public static func expansion(
of macro: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) -> ExprSyntax {
return """
try await {
print("let's throw")
return try await throwingFunc()
}()
"""
}
}

struct SimpleDiagnosticMessage: DiagnosticMessage {
let message: String
let diagnosticID: MessageID
Expand Down
12 changes: 12 additions & 0 deletions test/Macros/macro_expand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,18 @@ func testStringifyWithThrows() throws {
_ = #stringifyAndTry(maybeThrowing())
}

@available(SwiftStdlib 5.1, *)
func throwingFunc() async throws -> Int { 5 }

@freestanding(expression) macro callThrowingFunc<T>(_ body: () -> T) -> T = #externalMacro(module: "MacroDefinition", type: "TryCallThrowingFuncMacro")

@available(SwiftStdlib 5.1, *)
func testThrowingCall() async throws -> Int {
#callThrowingFunc {
[1, 2, 3, 4, 5].map { $0 + 1 }.first!
}
}

func testStringifyWithLocalType() throws {
_ = #stringify({
struct QuailError: Error {}
Expand Down