Merge pull request #2893 from MaxHaertwig/toggle-bool-correctable

Make `toggle_bool` rule substitution correctable
This commit is contained in:
Marcelo Fabri
2019-10-08 00:56:22 -07:00
committed by GitHub
3 changed files with 27 additions and 7 deletions
+3
View File
@@ -28,6 +28,9 @@
[Marcelo Fabri](https://github.com/marcelofabri)
[#2883](https://github.com/realm/SwiftLint/issues/2883)
* Make `toggle_bool` rule substitution correctable.
[MaxHaertwig](https://github.com/maxhaertwig)
#### Bug Fixes
* None.
+1 -1
View File
@@ -19447,7 +19447,7 @@ TODOs and FIXMEs should be resolved.
Identifier | Enabled by default | Supports autocorrection | Kind | Analyzer | Minimum Swift Compiler Version
--- | --- | --- | --- | --- | ---
`toggle_bool` | Disabled | No | idiomatic | No | 4.2.0
`toggle_bool` | Disabled | Yes | idiomatic | No | 4.2.0
Prefer `someBool.toggle()` over `someBool = !someBool`.
@@ -1,6 +1,7 @@
import Foundation
import SourceKittenFramework
public struct ToggleBoolRule: ConfigurationProviderRule, OptInRule, AutomaticTestableRule {
public struct ToggleBoolRule: SubstitutionCorrectableRule, ConfigurationProviderRule, OptInRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
@@ -22,16 +23,32 @@ public struct ToggleBoolRule: ConfigurationProviderRule, OptInRule, AutomaticTes
"↓isHidden = !isHidden\n",
"↓view.clipsToBounds = !view.clipsToBounds\n",
"func foo() { ↓abc = !abc }"
],
corrections: [
"↓isHidden = !isHidden\n": "isHidden.toggle()\n",
"↓view.clipsToBounds = !view.clipsToBounds\n": "view.clipsToBounds.toggle()\n",
"func foo() { ↓abc = !abc }": "func foo() { abc.toggle() }"
]
)
public func validate(file: File) -> [StyleViolation] {
let pattern = "(?<![\\w.])([\\w.]+) = !\\1\\b"
let excludingKinds = SyntaxKind.commentAndStringKinds
return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds).map {
StyleViolation(ruleDescription: type(of: self).description,
return violationRanges(in: file).map {
StyleViolation(ruleDescription: ToggleBoolRule.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
location: Location(file: file, characterOffset: $0.location)
)
}
}
public func violationRanges(in file: File) -> [NSRange] {
let pattern = "(?<![\\w.])([\\w.]+) = !\\1\\b"
let excludingKinds = SyntaxKind.commentAndStringKinds
return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds)
}
public func substitution(for violationRange: NSRange, in file: File) -> (NSRange, String) {
let violationString = file.contents.bridge().substring(with: violationRange)
let identifier = violationString.components(separatedBy: .whitespaces).first { !$0.isEmpty }
return (violationRange, identifier! + ".toggle()")
}
}