Skip to content

Add new example: Migrate a Swift Codebase to the new if-let-Syntax #887

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 2 commits into from
Oct 18, 2022
Merged
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
59 changes: 59 additions & 0 deletions Examples/MigrateToNewIfLetSyntax.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import Foundation
import SwiftSyntax
import SwiftParser

/// MigrateToNewIfLetSyntax will visit each `if` statement in the syntax tree
/// replacing all "old style" optional bindings by the new shorter syntax available
/// since Swift 5.7.
///
/// For example, it will turn:
/// ```
/// if let foo = foo {
/// ...
/// }
/// ```
/// into:
/// ```
/// if let foo {
/// ...
/// }
class MigrateToNewIfLetSyntax: SyntaxRewriter {
// Visit all `if` statements.
override func visit(_ node: IfStmtSyntax) -> StmtSyntax {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only if statements are currently considered, but optional bindings are allowed in guard and while statements as well. For an example, it might be fine to cover only one case and leave the rest up to the motivated user, though. 😉

Shameless plug by the way: There already is such a rule available in SwiftLint.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an example, it might be fine to cover only one case and leave the rest up to the motivated user, though.

That was exactly my thought 😉

// Visit all conditions in the node.
let newConditions = node.conditions.enumerated().map { (index, condition) in
var conditionCopy = condition
// Check if the condition is an optional binding ...
if var binding = condition.condition.as(OptionalBindingConditionSyntax.self),
// ... and has an initializer ...
let initializer = binding.initializer,
// ... and both sides of the assignment are the same identifiers.
binding.pattern.withoutTrivia().description == initializer.value.withoutTrivia().description {
// Remove the initializer ...
binding.initializer = nil
// ... and remove whitespace before the comma (in `if` statements with multiple conditions).
if index != node.conditions.count - 1 {
binding.pattern = binding.pattern.withoutTrailingTrivia()
}
conditionCopy.condition = Syntax(binding)
}
return conditionCopy
}
return StmtSyntax(node.withConditions(ConditionElementListSyntax(newConditions)))
}

/// Utility function to migrate all swift files in a folder and its subfolders
static func migrate(folderPath: String) {
for case let fileURL as String in FileManager.default.enumerator(atPath: folderPath)! {
if fileURL.hasSuffix("swift") {
print("Rewriting", fileURL)
let fullPath = folderPath + "/" + fileURL
let tree = try! Parser.parse(source: String(data: FileManager.default.contents(atPath: fullPath)!, encoding: .utf8 )!)
let newTree = MigrateToNewIfLetSyntax().visit(tree)
try! newTree.description.write(toFile: fullPath, atomically: true, encoding: .utf8)
}
}
}
}

MigrateToNewIfLetSyntax.migrate(folderPath: "/path/to/folder")