-
Notifications
You must be signed in to change notification settings - Fork 498
Refactor MoveMembersToExtension
#3265
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
5522021
e6cc240
7e0e90d
7d91d8a
0486a2d
866bab9
218c688
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors | ||
| // Licensed under Apache License v2.0 with Runtime Library Exception | ||
| // | ||
| // See https://swift.org/LICENSE.txt for license information | ||
| // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| #if compiler(>=6) | ||
| public import SwiftSyntax | ||
| #else | ||
| import SwiftSyntax | ||
| #endif | ||
|
|
||
| public struct MoveMembersToExtension: SyntaxRefactoringProvider { | ||
|
|
||
| public struct Context { | ||
| public let declName: TokenSyntax | ||
| public let selectedIdentifiers: [SyntaxIdentifier] | ||
|
||
|
|
||
| public init(declName: TokenSyntax, selectedIdentifiers: [SyntaxIdentifier]) { | ||
| self.declName = declName | ||
| self.selectedIdentifiers = selectedIdentifiers | ||
| } | ||
| } | ||
|
|
||
| public static func refactor(syntax: SourceFileSyntax, in context: Context) throws -> SourceFileSyntax { | ||
| guard | ||
| let decl = syntax.statements.first(where: { | ||
| $0.item.asProtocol(NamedDeclSyntax.self)?.name == context.declName | ||
| }), | ||
| let declGroup = decl.item.asProtocol(DeclGroupSyntax.self), | ||
| let index = syntax.statements.index(of: decl) | ||
| else { | ||
| throw RefactoringNotApplicableError("Type declaration not found") | ||
| } | ||
|
|
||
| let selectedMembers = declGroup.memberBlock.members.filter { context.selectedIdentifiers.contains($0.id) } | ||
|
|
||
| for member in selectedMembers { | ||
| try validateMember(member) | ||
| } | ||
|
|
||
| let remainingMembers = declGroup.memberBlock.members.filter { !context.selectedIdentifiers.contains($0.id) } | ||
|
|
||
| let updatedMemberBlock = declGroup.memberBlock.with(\.members, remainingMembers) | ||
| let updatedDeclGroup = declGroup.with(\.memberBlock, updatedMemberBlock) | ||
ahoppen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| let updatedItem = decl.with(\.item, .decl(DeclSyntax(updatedDeclGroup))) | ||
|
|
||
| let extensionMemberBlockSyntax = declGroup.memberBlock.with(\.members, selectedMembers) | ||
|
|
||
| let extensionDecl = ExtensionDeclSyntax( | ||
| leadingTrivia: .newlines(2), | ||
| extendedType: IdentifierTypeSyntax( | ||
| leadingTrivia: .space, | ||
| name: context.declName | ||
| ), | ||
| memberBlock: extensionMemberBlockSyntax | ||
| ) | ||
|
|
||
| var updatedStatements = syntax.statements | ||
| updatedStatements.remove(at: index) | ||
| updatedStatements.insert(updatedItem, at: index) | ||
ahoppen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| updatedStatements.append(CodeBlockItemSyntax(item: .decl(DeclSyntax(extensionDecl)))) | ||
|
||
|
|
||
| return syntax.with(\.statements, updatedStatements) | ||
| } | ||
|
|
||
| private static func validateMember(_ member: MemberBlockItemSyntax) throws { | ||
| if member.decl.is(AccessorDeclSyntax.self) || member.decl.is(DeinitializerDeclSyntax.self) | ||
| || member.decl.is(EnumCaseDeclSyntax.self) | ||
| { | ||
| throw RefactoringNotApplicableError("Cannot move this type of declaration") | ||
|
||
| } | ||
|
|
||
| if let varDecl = member.decl.as(VariableDeclSyntax.self), | ||
| varDecl.bindings.contains(where: { $0.initializer == nil }) | ||
| { | ||
| throw RefactoringNotApplicableError("Cannot move stored properties to extension") | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors | ||
| // Licensed under Apache License v2.0 with Runtime Library Exception | ||
| // | ||
| // See https://swift.org/LICENSE.txt for license information | ||
| // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import SwiftParser | ||
| import SwiftRefactor | ||
| import SwiftSyntax | ||
| import SwiftSyntaxBuilder | ||
| import XCTest | ||
| import _SwiftSyntaxTestSupport | ||
|
|
||
| final class MoveMembersToExtensionTests: XCTestCase { | ||
| func testMoveFunctionToExtension() throws { | ||
| let baseline: String = """ | ||
| class Foo {1️⃣ | ||
| func foo() { | ||
| print("Hello world!") | ||
| }2️⃣ | ||
|
|
||
| func bar() { | ||
| print("Hello world!") | ||
| } | ||
| } | ||
| """ | ||
|
|
||
| let expected: SourceFileSyntax = """ | ||
| class Foo { | ||
|
|
||
| func bar() { | ||
| print("Hello world!") | ||
| } | ||
| } | ||
|
|
||
| extension Foo { | ||
| func foo() { | ||
| print("Hello world!") | ||
| } | ||
| } | ||
| """ | ||
|
|
||
| let (markers, source) = extractMarkers(baseline) | ||
|
|
||
| var parser = Parser(source) | ||
| let tree = SourceFileSyntax.parse(from: &parser) | ||
| let context = makeContextFromClass(markers: markers, source: tree) | ||
| try assertRefactorConvert(tree, expected: expected, context: context) | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should make sure that we either disallow or correctly handle extracting members from nested types. Suggested test cases: struct Outer {
struct Inner {
func moveThis() {}
}
}struct Outer<T> {
struct Inner {
func moveThis() {}
}
}func outer() {
struct Inner {
func moveThis() {}
}
}
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a couple of tests, the rest are in progress. |
||
| } | ||
|
|
||
| private func makeContextFromClass(markers: [String: Int], source: SourceFileSyntax) -> MoveMembersToExtension.Context { | ||
| let classDecl = source.statements | ||
| .first(where: { $0.item.is(ClassDeclSyntax.self) })! | ||
| .item.cast(ClassDeclSyntax.self) | ||
| let members = classDecl.memberBlock.members | ||
|
|
||
| let selectedMembersId: [SyntaxIdentifier] = members.compactMap({ | ||
| let offset = $0.positionAfterSkippingLeadingTrivia.utf8Offset | ||
| if let start = markers["1️⃣"], let end = markers["2️⃣"], offset > start && offset < end { | ||
| return $0.id | ||
| } | ||
| return nil | ||
| }) | ||
|
|
||
| return MoveMembersToExtension.Context(declName: classDecl.name, selectedIdentifiers: selectedMembersId) | ||
| } | ||
|
|
||
| private func assertRefactorConvert( | ||
| _ callDecl: SourceFileSyntax, | ||
| expected: SourceFileSyntax?, | ||
| context: MoveMembersToExtension.Context, | ||
| file: StaticString = #filePath, | ||
| line: UInt = #line | ||
| ) throws { | ||
| try assertRefactor( | ||
| callDecl, | ||
| context: context, | ||
| provider: MoveMembersToExtension.self, | ||
| expected: expected, | ||
| file: file, | ||
| line: line | ||
| ) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.