Skip to content
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

Convert implicitly unwrapped optionals to proper optionals #1539

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions Sources/SourceKitLSP/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ target_sources(SourceKitLSP PRIVATE
Swift/AdjustPositionToStartOfIdentifier.swift
Swift/CodeActions/AddDocumentation.swift
Swift/CodeActions/ConvertIntegerLiteral.swift
Swift/CodeActions/ConvertImplicitlyUnwrappedOptionalToOptional.swift
Swift/CodeActions/ConvertJSONToCodableStruct.swift
Swift/CodeActions/PackageManifestEdits.swift
Swift/CodeActions/SyntaxCodeActionProvider.swift
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 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 LanguageServerProtocol
import SwiftRefactor
import SwiftSyntax

/// Convert implicitly unwrapped optionals to optionals
struct ConvertImplicitlyUnwrappedOptionalToOptional: SyntaxRefactoringProvider {
public static func refactor(syntax: ImplicitlyUnwrappedOptionalTypeSyntax, in context: Void) -> OptionalTypeSyntax? {
OptionalTypeSyntax(
leadingTrivia: syntax.leadingTrivia,
syntax.unexpectedBeforeWrappedType,
wrappedType: syntax.wrappedType,
syntax.unexpectedBetweenWrappedTypeAndExclamationMark,
questionMark: .postfixQuestionMarkToken(
leadingTrivia: syntax.exclamationMark.leadingTrivia,
trailingTrivia: syntax.exclamationMark.trailingTrivia
)
)
}
}

extension ConvertImplicitlyUnwrappedOptionalToOptional: SyntaxRefactoringCodeActionProvider {
static let title: String = "Convert Implicitly Unwrapped Optional to Optional"

static func nodeToRefactor(in scope: SyntaxCodeActionScope) -> ImplicitlyUnwrappedOptionalTypeSyntax? {
guard let token = scope.innermostNodeContainingRange else {
return nil
}

return
if let iuoType = token.as(ImplicitlyUnwrappedOptionalTypeSyntax.self)
?? token.parent?.as(ImplicitlyUnwrappedOptionalTypeSyntax.self)
{
iuoType
} else if token.is(TokenSyntax.self),
let wrappedType = token.parent?.as(TypeSyntax.self),
let iuoType = wrappedType.parent?.as(ImplicitlyUnwrappedOptionalTypeSyntax.self),
iuoType.wrappedType == wrappedType
{
iuoType
} else {
nil
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ let allSyntaxCodeActions: [SyntaxCodeActionProvider.Type] = [
AddDocumentation.self,
AddSeparatorsToIntegerLiteral.self,
ConvertIntegerLiteral.self,
ConvertImplicitlyUnwrappedOptionalToOptional.self,
ConvertJSONToCodableStruct.self,
FormatRawStringLiteral.self,
MigrateToNewIfLetSyntax.self,
Expand Down
28 changes: 28 additions & 0 deletions Tests/SourceKitLSPTests/CodeActionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,34 @@ final class CodeActionTests: XCTestCase {
}
}

func testConvertIUOToProperOptional() async throws {
try await assertCodeActions(
"""
func (a: 1️⃣(String, /* tuple */ Int)!2️⃣/*tra3️⃣iling*/4️⃣)
""",
markers: ["1️⃣", "2️⃣", "3️⃣"],
ranges: [("1️⃣", "2️⃣"), ("1️⃣", "3️⃣")],
exhaustive: false
) { uri, positions in
[
CodeAction(
title: "Convert Implicitly Unwrapped Optional to Optional",
kind: .refactorInline,
edit: WorkspaceEdit(
changes: [
uri: [
TextEdit(
range: positions["1️⃣"]..<positions["4️⃣"],
newText: "(String, /* tuple */ Int)?/*trailing*/"
)
]
]
)
)
]
}
}

/// Retrieves the code action at a set of markers and asserts that it matches a list of expected code actions.
///
/// - Parameters:
Expand Down