Skip to content

[Macros] Don't expand macros inside macro expession arguments #65519

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 1 commit into from
May 1, 2023
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
10 changes: 9 additions & 1 deletion lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5389,7 +5389,15 @@ namespace {
E->setMacroRef(macroRef);
E->setType(expandedType);

if (!cs.Options.contains(ConstraintSystemFlags::DisableMacroExpansions)) {
// FIXME: Expansion should be lazy.
// i.e. 'ExpandMacroExpansionExprRequest' should be sinked into
// 'getRewritten()', and performed on-demand.
if (!cs.Options.contains(ConstraintSystemFlags::DisableMacroExpansions) &&
// Do not expand macros inside macro arguments. For example for
// '#stringify(#assert(foo))' when typechecking `#assert(foo)`,
// we don't want to expand it.
llvm::none_of(makeArrayRef(ExprStack).drop_back(1),
[](Expr *E) { return isa<MacroExpansionExpr>(E); })) {
(void)evaluateOrDefault(cs.getASTContext().evaluator,
ExpandMacroExpansionExprRequest{E}, None);
}
Expand Down
14 changes: 14 additions & 0 deletions test/Macros/macro_expand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,20 @@ func testDiscardableStringify(x: Int) {
}
#endif

#if TEST_DIAGNOSTICS
// This causes an error when non-'Bool' value is passed.
@freestanding(expression) macro assertAny<T>(_ value: T) = #externalMacro(module: "MacroDefinition", type: "AssertMacro")

func testNested() {
struct Nested { }
_ = #stringify(#assertAny(Nested()))
// expected-note@-1 2 {{in expansion of macro 'stringify' here}}
// CHECK-DIAGS-NOT: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// CHECK-DIAGS: @__swiftmacro_9MacroUser10testNestedyyF9stringifyfMf_9assertAnyfMf_.swift:1:8: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// CHECK-DIAGS-NOT: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
}
#endif

func testStringifyWithThrows() throws {
// Okay, we can put the try inside or outside
_ = try #stringify(maybeThrowing())
Expand Down