Skip to content

Commit ed4ce5c

Browse files
committed
[Macros] Validate freestanding macro expansions.
1 parent b0a0867 commit ed4ce5c

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

lib/Sema/TypeCheckMacros.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,10 @@ swift::expandFreestandingDeclarationMacro(MacroExpansionDecl *med) {
908908
/*parsingOpts=*/{}, /*isPrimary=*/false);
909909
macroSourceFile->setImports(sourceFile->getImports());
910910

911+
validateMacroExpansion(macroSourceFile, macro,
912+
/*attachedTo*/nullptr,
913+
MacroRole::Declaration);
914+
911915
PrettyStackTraceDecl debugStack(
912916
"type checking expanded declaration macro", med);
913917

test/Macros/Inputs/syntax_macro_definitions.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -764,7 +764,7 @@ public struct AddCompletionHandler: PeerMacro {
764764
}
765765
}
766766

767-
public struct InvalidMacro: PeerMacro {
767+
public struct InvalidMacro: PeerMacro, DeclarationMacro {
768768
public static func expansion(
769769
of node: AttributeSyntax,
770770
providingPeersOf declaration: some DeclSyntaxProtocol,
@@ -794,6 +794,15 @@ public struct InvalidMacro: PeerMacro {
794794
"typealias _FileReferenceLiteralType = Void",
795795
]
796796
}
797+
798+
public static func expansion(
799+
of node: some FreestandingMacroExpansionSyntax,
800+
in context: some MacroExpansionContext
801+
) throws -> [DeclSyntax] {
802+
return [
803+
"var value: Int"
804+
]
805+
}
797806
}
798807

799808
public struct WrapInType: PeerMacro {

test/Macros/macro_expand.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@
2727
// REQUIRES: OS=macosx
2828

2929
#if TEST_DIAGNOSTICS
30+
@freestanding(declaration)
31+
macro NotCovered() = #externalMacro(module: "MacroDefinition", type: "InvalidMacro")
32+
33+
struct MemberNotCovered {
34+
#NotCovered
35+
// expected-note@-1 {{in expansion of macro 'NotCovered' here}}
36+
37+
// CHECK-DIAGS: error: declaration name 'value' is not covered by macro 'NotCovered'
38+
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser16MemberNotCoveredV0dE0fMf0_.swift
39+
// CHECK-DIAGS: var value: Int
40+
// CHECK-DIAGS: END CONTENTS OF FILE
41+
}
42+
3043
@attached(peer)
3144
macro Invalid() = #externalMacro(module: "MacroDefinition", type: "InvalidMacro")
3245

0 commit comments

Comments
 (0)