Skip to content

[5.9] Add convert to trailing closure and editor placeholder refactorings #1806

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 6 commits into from
Jun 21, 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
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,12 @@ let package = Package(

.target(
name: "SwiftRefactor",
dependencies: ["SwiftParser", "SwiftSyntax"]
dependencies: ["SwiftBasicFormat", "SwiftParser", "SwiftSyntax", "SwiftSyntaxBuilder"]
),

.testTarget(
name: "SwiftRefactorTest",
dependencies: ["_SwiftSyntaxTestSupport", "SwiftRefactor", "SwiftSyntaxBuilder"]
dependencies: ["_SwiftSyntaxTestSupport", "SwiftRefactor"]
),

// MARK: - Executable targets
Expand Down
3 changes: 1 addition & 2 deletions Sources/SwiftBasicFormat/BasicFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ open class BasicFormat: SyntaxRewriter {
(.keyword(.set), .leftParen), // var mYar: Int { set(value) {} }
(.keyword(.subscript), .leftParen), // subscript(x: Int)
(.keyword(.super), .period), // super.someProperty
(.leftBrace, _),
(.leftBrace, .rightBrace), // {}
(.leftParen, _),
(.leftSquareBracket, _),
(.multilineStringQuote, .rawStringDelimiter), // closing raw string delimiter should never be separate by a space
Expand Down Expand Up @@ -245,7 +245,6 @@ open class BasicFormat: SyntaxRewriter {
(_, .exclamationMark),
(_, .postfixOperator),
(_, .postfixQuestionMark),
(_, .rightBrace),
(_, .rightParen),
(_, .rightSquareBracket),
(_, .semicolon),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import SwiftSyntax
/// 0xF_FFFF_FFFF
/// 0b1_010
/// ```
public struct AddSeparatorsToIntegerLiteral: RefactoringProvider {
public struct AddSeparatorsToIntegerLiteral: SyntaxRefactoringProvider {
public static func refactor(syntax lit: IntegerLiteralExprSyntax, in context: Void) -> IntegerLiteralExprSyntax? {
if lit.digits.text.contains("_") {
guard let strippedLiteral = RemoveSeparatorsFromIntegerLiteral.refactor(syntax: lit) else {
Expand Down
149 changes: 149 additions & 0 deletions Sources/SwiftRefactor/CallToTrailingClosures.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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 SwiftBasicFormat
import SwiftSyntax

/// Convert a call with inline closures to one that uses trailing closure
/// syntax. Returns `nil` if there's already trailing closures or there are no
/// closures within the call. Pass `startAtArgument` to specify the argument
/// index to start the conversion from, ie. to skip converting closures before
/// `startAtArgument`.
///
/// ## Before
/// ```
/// someCall(closure1: { arg in
/// return 1
/// }, closure2: { arg in
/// return 2
/// })
/// ```
///
/// ## After
/// ```
/// someCall { arg in
/// return 1
/// } closure2: { arg in
/// return 2
/// }
/// ```
public struct CallToTrailingClosures: SyntaxRefactoringProvider {
public struct Context {
public let startAtArgument: Int

public init(startAtArgument: Int = 0) {
self.startAtArgument = startAtArgument
}
}

// TODO: Rather than returning nil, we should consider throwing errors with
// appropriate messages instead.
public static func refactor(syntax call: FunctionCallExprSyntax, in context: Context = Context()) -> FunctionCallExprSyntax? {
return call.convertToTrailingClosures(from: context.startAtArgument)?.formatted().as(FunctionCallExprSyntax.self)
}
}

extension FunctionCallExprSyntax {
fileprivate func convertToTrailingClosures(from startAtArgument: Int) -> FunctionCallExprSyntax? {
guard trailingClosure == nil, additionalTrailingClosures == nil, leftParen != nil, rightParen != nil else {
// Already have trailing closures
return nil
}

var closures = [(original: TupleExprElementSyntax, closure: ClosureExprSyntax)]()
for arg in argumentList.dropFirst(startAtArgument) {
guard var closure = arg.expression.as(ClosureExprSyntax.self) else {
closures.removeAll()
continue
}

// Trailing comma won't exist any more, move its trivia to the end of
// the closure instead
if let comma = arg.trailingComma {
closure = closure.with(\.trailingTrivia, closure.trailingTrivia.merging(triviaOf: comma))
}
closures.append((arg, closure))
}

guard !closures.isEmpty else {
return nil
}

// First trailing closure won't have label/colon. Transfer their trivia.
var trailingClosure = closures.first!.closure
.with(
\.leadingTrivia,
Trivia()
.merging(triviaOf: closures.first!.original.label)
.merging(triviaOf: closures.first!.original.colon)
.merging(closures.first!.closure.leadingTrivia)
)
let additionalTrailingClosures = closures.dropFirst().map {
MultipleTrailingClosureElementSyntax(
label: $0.original.label ?? .wildcardToken(),
colon: $0.original.colon ?? .colonToken(),
closure: $0.closure
)
}

var converted = self.detach()

// Remove parens if there's no non-closure arguments left and remove the
// last comma otherwise. Makes sure to keep the trivia of any removed node.
var argList = Array(argumentList.dropLast(closures.count))
if argList.isEmpty {
converted =
converted
.with(\.leftParen, nil)
.with(\.rightParen, nil)

// No left paren any more, right paren is handled below since it makes
// sense to keep its trivia of the end of the call, regardless of whether
// it was removed or not.
if let leftParen = leftParen {
trailingClosure = trailingClosure.with(
\.leadingTrivia,
Trivia()
.merging(triviaOf: leftParen)
.merging(trailingClosure.leadingTrivia)
)
}
} else {
let last = argList.last!
if let comma = last.trailingComma {
converted =
converted
.with(\.rightParen, TokenSyntax.rightParenToken(trailingTrivia: Trivia().merging(triviaOf: comma)))
}
argList[argList.count - 1] =
last
.with(\.trailingComma, nil)
}

// Update arguments and trailing closures
converted =
converted
.with(\.argumentList, TupleExprElementListSyntax(argList))
.with(\.trailingClosure, trailingClosure)
if !additionalTrailingClosures.isEmpty {
converted = converted.with(\.additionalTrailingClosures, MultipleTrailingClosureElementListSyntax(additionalTrailingClosures))
}

// The right paren either doesn't exist any more, or is before all the
// trailing closures. Moves its trivia to the end of the converted call.
if let rightParen = rightParen {
converted = converted.with(\.trailingTrivia, converted.trailingTrivia.merging(triviaOf: rightParen))
}

return converted
}
}
Loading