Skip to content

Commit

Permalink
Add parentheses to corrected opaque and existential optionals (#5278)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimplyDanny authored Oct 15, 2023
1 parent 2ed1fc2 commit 73e6ba3
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@

#### Bug Fixes

* Fix invalid corrections for opaque and existential optionals in
`syntactic_sugar` rule.
[SimplyDanny](https://github.com/SimplyDanny)
[#5277](https://github.com/realm/SwiftLint/issues/5277)

* Fix false positive in `unused_import` rule that triggered on
`@_exported` imports which could break downstream modules if removed.
[jszumski](https://github.com/jszumski)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,10 @@ private struct CorrectingContext<R: Rule> {
correctViolations(violationsBeforeComma)
replaceCharacters(in: leftRange, with: "[")

case .optional where typeIsOpaqueOrExistential(correction: correction):
replaceCharacters(in: rightRange, with: ")?")
correctViolations(violation.children)
replaceCharacters(in: leftRange, with: "(")
case .optional:
replaceCharacters(in: rightRange, with: "?")
correctViolations(violation.children)
Expand All @@ -310,6 +314,14 @@ private struct CorrectingContext<R: Rule> {
corrections.append(Correction(ruleDescription: type(of: rule).description, location: location))
}

private func typeIsOpaqueOrExistential(correction: SyntacticSugarRuleViolation.Correction) -> Bool {
if let innerTypeRange = file.stringView.NSRange(start: correction.leftEnd, end: correction.rightStart) {
let innerTypeString = file.stringView.substring(with: innerTypeRange)
return innerTypeString.contains("any ") || innerTypeString.contains("some ")
}
return false
}

private mutating func replaceCharacters(in range: NSRange, with replacement: String) {
contents = contents.bridge().replacingCharacters(in: range, with: replacement)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ internal enum SyntacticSugarRuleExamples {
Example("let x: Dictionary<Int, String>"): Example("let x: [Int: String]"),
Example("let x: Optional<Int>"): Example("let x: Int?"),
Example("let x: Optional< Int >"): Example("let x: Int?"),
Example("func f() -> Optional<any Foo> {}"): Example("func f() -> (any Foo)? {}"),
Example("func f() -> Optional<some Foo> {}"): Example("func f() -> (some Foo)? {}"),

Example("let x: Dictionary<Int , String>"): Example("let x: [Int: String]"),
Example("let x: Swift.Optional<String>"): Example("let x: String?"),
Expand Down

0 comments on commit 73e6ba3

Please sign in to comment.