Skip to content

Commit fef7ff9

Browse files
committed
-
1 parent 4715a6a commit fef7ff9

2 files changed

Lines changed: 47 additions & 6 deletions

File tree

Sources/PrincipleMacros/Syntax/Extensions/IfConfigDeclSyntax+EnclosingIfConfig.swift

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,15 +95,22 @@ extension DeclSyntaxProtocol {
9595
public func applyingEnclosingIfConfig(
9696
to members: MemberBlockItemListSyntax
9797
) -> IfConfigDeclSyntax? {
98-
guard var parent = parent?.parent?.as(MemberBlockItemListSyntax.self) else {
98+
guard var ancestor = parent?.parent?.parent?.as(IfConfigClauseSyntax.self) else {
9999
return nil
100100
}
101101

102-
parent.replaceSubrange(
103-
parent.startIndex ..< parent.endIndex,
104-
with: members
105-
)
102+
ancestor = ancestor.with(\.elements, .decls(members.withLeadingNewline))
103+
return ancestor.enclosingIfConfig
104+
}
105+
106+
public func applyingEnclosingIfConfig(
107+
to statements: CodeBlockItemListSyntax
108+
) -> IfConfigDeclSyntax? {
109+
guard var ancestor = parent?.parent?.parent?.as(IfConfigClauseSyntax.self) else {
110+
return nil
111+
}
106112

107-
return parent.withLeadingNewline.enclosingIfConfig
113+
ancestor = ancestor.with(\.elements, .statements(statements.withLeadingNewline))
114+
return ancestor.enclosingIfConfig
108115
}
109116
}

Tests/PrincipleMacrosTests/Syntax/Extensions/IfConfigDeclSyntaxTests.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,40 @@ internal enum IfConfigDeclSyntaxTests {
163163
#expect(ifConfig?.description == expectation)
164164
}
165165

166+
@Test
167+
func applyToNewStatements() throws {
168+
let decl: DeclSyntax = """
169+
class MyClass {
170+
#if DEBUG
171+
var other = "hello"
172+
#else
173+
#if os(macOS)
174+
var test = 123
175+
#endif
176+
#endif
177+
}
178+
"""
179+
180+
let newStatements: CodeBlockItemListSyntax = """
181+
var replacement = "Hello"
182+
func test() {}
183+
"""
184+
185+
let expectation = """
186+
#if DEBUG
187+
#else
188+
#if os(macOS)
189+
var replacement = "Hello"
190+
func test() {}
191+
#endif
192+
#endif
193+
"""
194+
195+
let property = try parseLastProperty(in: decl)
196+
let ifConfig = property.underlying.applyingEnclosingIfConfig(to: newStatements)
197+
#expect(ifConfig?.description == expectation)
198+
}
199+
166200
// swiftlint:enable empty_line_after_type_declaration
167201
}
168202
}

0 commit comments

Comments
 (0)