|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import LanguageServerProtocol |
| 14 | +import SwiftRefactor |
| 15 | +import SwiftSyntax |
| 16 | + |
| 17 | +/// Convert implicitly unwrapped optionals (IUOs) to proper optionals |
| 18 | +@_spi(Testing) |
| 19 | +public struct ConvertIUOToProperOptional: SyntaxRefactoringProvider { |
| 20 | + public typealias Input = ImplicitlyUnwrappedOptionalTypeSyntax |
| 21 | + public typealias Context = Void |
| 22 | + public typealias Output = OptionalTypeSyntax |
| 23 | + |
| 24 | + @_spi(Testing) |
| 25 | + public static func refactor(syntax: Input, in context: Context) -> Output? { |
| 26 | + OptionalTypeSyntax( |
| 27 | + leadingTrivia: syntax.leadingTrivia, |
| 28 | + syntax.unexpectedBeforeWrappedType, |
| 29 | + wrappedType: syntax.wrappedType, |
| 30 | + syntax.unexpectedBetweenWrappedTypeAndExclamationMark, |
| 31 | + questionMark: .postfixQuestionMarkToken( |
| 32 | + leadingTrivia: syntax.exclamationMark.leadingTrivia, |
| 33 | + trailingTrivia: syntax.exclamationMark.trailingTrivia |
| 34 | + ) |
| 35 | + ) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +extension ConvertIUOToProperOptional: SyntaxRefactoringCodeActionProvider { |
| 40 | + static let title: String = "Convert Implicitly Unwrapped Optional to Proper Optional" |
| 41 | + |
| 42 | + static func nodeToRefactor(in scope: SyntaxCodeActionScope) -> Input? { |
| 43 | + guard let token = scope.innermostNodeContainingRange else { |
| 44 | + return nil |
| 45 | + } |
| 46 | + |
| 47 | + return if let iuoType = token.as(Input.self) ?? token.parent?.as(Input.self) { |
| 48 | + iuoType |
| 49 | + } else if token.is(TokenSyntax.self), |
| 50 | + let wrappedType = token.parent?.as(TypeSyntax.self), |
| 51 | + let iuoType = wrappedType.parent?.as(Input.self), |
| 52 | + iuoType.wrappedType == wrappedType |
| 53 | + { |
| 54 | + iuoType |
| 55 | + } else { |
| 56 | + nil |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments