|
| 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 to optionals |
| 18 | +struct ConvertImplicitlyUnwrappedOptionalToOptional: SyntaxRefactoringProvider { |
| 19 | + public static func refactor(syntax: ImplicitlyUnwrappedOptionalTypeSyntax, in context: Void) -> OptionalTypeSyntax? { |
| 20 | + OptionalTypeSyntax( |
| 21 | + leadingTrivia: syntax.leadingTrivia, |
| 22 | + syntax.unexpectedBeforeWrappedType, |
| 23 | + wrappedType: syntax.wrappedType, |
| 24 | + syntax.unexpectedBetweenWrappedTypeAndExclamationMark, |
| 25 | + questionMark: .postfixQuestionMarkToken( |
| 26 | + leadingTrivia: syntax.exclamationMark.leadingTrivia, |
| 27 | + trailingTrivia: syntax.exclamationMark.trailingTrivia |
| 28 | + ) |
| 29 | + ) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +extension ConvertImplicitlyUnwrappedOptionalToOptional: SyntaxRefactoringCodeActionProvider { |
| 34 | + static let title: String = "Convert Implicitly Unwrapped Optional to Optional" |
| 35 | + |
| 36 | + static func nodeToRefactor(in scope: SyntaxCodeActionScope) -> ImplicitlyUnwrappedOptionalTypeSyntax? { |
| 37 | + guard let token = scope.innermostNodeContainingRange else { |
| 38 | + return nil |
| 39 | + } |
| 40 | + |
| 41 | + return |
| 42 | + if let iuoType = token.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) |
| 43 | + ?? token.parent?.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) |
| 44 | + { |
| 45 | + iuoType |
| 46 | + } else if token.is(TokenSyntax.self), |
| 47 | + let wrappedType = token.parent?.as(TypeSyntax.self), |
| 48 | + let iuoType = wrappedType.parent?.as(ImplicitlyUnwrappedOptionalTypeSyntax.self), |
| 49 | + iuoType.wrappedType == wrappedType |
| 50 | + { |
| 51 | + iuoType |
| 52 | + } else { |
| 53 | + nil |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments