Skip to content

Commit 8520829

Browse files
authored
Allow inout parameters in expression macros (#82370)
Sema seems to be flagging inout expressions (e.g. &foo) in expression macros as invalid, setting up a catch 22 where Sema emits an error when a parameter has the '&' sigil and type checking fails when it doesn't. This resolves the issue by allowing inout expressions inside macro expansion expressions. Resolves #82369.
1 parent 00fcb51 commit 8520829

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

lib/Sema/PreCheckTarget.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,8 +1315,9 @@ class PreCheckTarget final : public ASTWalker {
13151315
lastInnerParenLoc = PE->getLParenLoc();
13161316
parent = nextParent;
13171317
}
1318-
1319-
if (isa<ApplyExpr>(parent) || isa<UnresolvedMemberExpr>(parent)) {
1318+
1319+
if (isa<ApplyExpr>(parent) || isa<UnresolvedMemberExpr>(parent) ||
1320+
isa<MacroExpansionExpr>(parent)) {
13201321
// If outermost paren is associated with a call or
13211322
// a member reference, it might be valid to have `&`
13221323
// before all of the parens.

test/Macros/Inputs/syntax_macro_definitions.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,15 @@ public class TupleMacro: ExpressionMacro {
240240
}
241241
}
242242

243+
public class VoidExpressionMacro: ExpressionMacro {
244+
public static func expansion(
245+
of macro: some FreestandingMacroExpansionSyntax,
246+
in context: some MacroExpansionContext
247+
) -> ExprSyntax {
248+
return "()"
249+
}
250+
}
251+
243252
enum CustomError: Error, CustomStringConvertible {
244253
case message(String)
245254

test/Macros/top_level_freestanding.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,23 @@ struct S {
145145
#checkGeneric<String>()
146146
#checkGeneric2<String, Int>()
147147
#checkGenericHashableCodable<String, Int>()
148+
149+
// Check that inout parameters are allowed in expression macros
150+
151+
@freestanding(expression) macro functionCallWithInoutParam(_ v: inout Int)
152+
= #externalMacro(module: "MacroDefinition", type: "VoidExpressionMacro")
153+
154+
@freestanding(expression) macro functionCallWithTwoInoutParams(_ u: inout Int, _ v: inout Int)
155+
= #externalMacro(module: "MacroDefinition", type: "VoidExpressionMacro")
156+
157+
@freestanding(expression) macro functionCallWithInoutParamPlusOthers(
158+
string: String, double: Double, _ v: inout Int)
159+
= #externalMacro(module: "MacroDefinition", type: "VoidExpressionMacro")
160+
161+
func testFunctionCallWithInoutParam() {
162+
var a = 0
163+
var b = 0
164+
#functionCallWithInoutParam(&a)
165+
#functionCallWithTwoInoutParams(&a, &b)
166+
#functionCallWithInoutParamPlusOthers(string: "", double: 1.0, &a)
167+
}

0 commit comments

Comments
 (0)