From ee3c2ab49afc80ee4ba5eb3cf0cc9ee02c3c9daf Mon Sep 17 00:00:00 2001 From: Rintaro Ishizaki Date: Tue, 6 May 2025 16:42:19 -0700 Subject: [PATCH] [Macros] Don't include attr range when checking macro definition For macro definition checking, we use the range of the `macro` declaration and re-parse it with `SwiftParser`. Previously it uses the range including the attributes, but that can result invalid code because the attribute can be in a `#if ... #endif` region. Since we don't use attributes for checking the definition, just use the range without the attributes instead. rdar://150805795 (cherry picked from commit 8519e71602a46e7dafd831e100ca6cb6b4ba85a0) --- lib/Sema/TypeCheckMacros.cpp | 2 +- test/Macros/macros_diagnostics.swift | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/Sema/TypeCheckMacros.cpp b/lib/Sema/TypeCheckMacros.cpp index d5b8614384748..305be67eb1557 100644 --- a/lib/Sema/TypeCheckMacros.cpp +++ b/lib/Sema/TypeCheckMacros.cpp @@ -136,7 +136,7 @@ MacroDefinition MacroDefinitionRequest::evaluate( SM.getEntireTextForBuffer(sourceFile->getBufferID()); StringRef macroDeclText = SM.extractText(Lexer::getCharSourceRangeFromSourceRange( - SM, macro->getSourceRangeIncludingAttrs())); + SM, macro->getSourceRange())); auto checkResult = swift_Macros_checkMacroDefinition( &ctx.Diags, sourceFileText, macroDeclText, &externalMacroName, diff --git a/test/Macros/macros_diagnostics.swift b/test/Macros/macros_diagnostics.swift index 22bc34aed6c8c..60af15973b76c 100644 --- a/test/Macros/macros_diagnostics.swift +++ b/test/Macros/macros_diagnostics.swift @@ -234,3 +234,10 @@ func someGlobalNext( ) async throws { fatalError() } + +// This is testing if the definition is actually checked. The error means the '#externalMacro' was correctly parsed and checked. +#if true +@available(*, unavailable) +#endif +@freestanding(expression) public macro MacroWithIfConfigAttr() = #externalMacro(module: "ThisMacroModuleDoesNotExist", type: "ThisMacroTypeDoesNotExist") +// expected-warning@-1{{external macro implementation type 'ThisMacroModuleDoesNotExist.ThisMacroTypeDoesNotExist'}}