Skip to content

Commit 613ec88

Browse files
authored
Merge pull request #64132 from hborla/validate-freestanding-macro-expansions
[Macros] Validate freestanding macro expansions.
2 parents d7123c7 + ed4ce5c commit 613ec88

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
@@ -913,6 +913,10 @@ swift::expandFreestandingMacro(MacroExpansionDecl *med) {
913913
/*parsingOpts=*/{}, /*isPrimary=*/false);
914914
macroSourceFile->setImports(sourceFile->getImports());
915915

916+
validateMacroExpansion(macroSourceFile, macro,
917+
/*attachedTo*/nullptr,
918+
MacroRole::Declaration);
919+
916920
PrettyStackTraceDecl debugStack(
917921
"type checking expanded declaration macro", med);
918922

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
@@ -31,6 +31,19 @@
3131
// REQUIRES: OS=macosx
3232

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

0 commit comments

Comments
 (0)