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

Add ReduceBooleanRule #2675

Merged
merged 7 commits into from
Mar 10, 2019
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@

#### Enhancements

* Add `reduce_boolean` rule to prefer simpler constructs over `reduce(Boolean)`.
[Xavier Lowmiller](https://github.com/xavierLowmiller)
[#2675](https://github.com/realm/SwiftLint/issues/2675)

* Add `nsobject_prefer_isequal` rule to warn against implementing `==` on an
`NSObject` subclass as calling `isEqual` (i.e. when using the class from
Objective-C) will will not use the defined `==` method.
Expand Down
62 changes: 62 additions & 0 deletions Rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
* [Quick Discouraged Call](#quick-discouraged-call)
* [Quick Discouraged Focused Test](#quick-discouraged-focused-test)
* [Quick Discouraged Pending Test](#quick-discouraged-pending-test)
* [Reduce Boolean](#reduce-boolean)
* [Redundant Discardable Let](#redundant-discardable-let)
* [Redundant Nil Coalescing](#redundant-nil-coalescing)
* [Redundant @objc Attribute](#redundant-@objc-attribute)
Expand Down Expand Up @@ -15783,6 +15784,67 @@ class TotoTests: QuickSpec {



## Reduce Boolean

Identifier | Enabled by default | Supports autocorrection | Kind | Analyzer | Minimum Swift Compiler Version
--- | --- | --- | --- | --- | ---
`reduce_boolean` | Enabled | No | performance | No | 4.2.0

Prefer using `.allSatisfy()` or `.contains()` over `reduce(true)` or `reduce(false)`

### Examples

<details>
<summary>Non Triggering Examples</summary>

```swift
nums.reduce(0) { $0.0 + $0.1 }
```

```swift
nums.reduce(0.0) { $0.0 + $0.1 }
```

</details>
<details>
<summary>Triggering Examples</summary>

```swift
let allNines = nums.↓reduce(true) { $0.0 && $0.1 == 9 }
```

```swift
let anyNines = nums.↓reduce(false) { $0.0 || $0.1 == 9 }
```

```swift
let allValid = validators.↓reduce(true) { $0 && $1(input) }
```

```swift
let anyValid = validators.↓reduce(false) { $0 || $1(input) }
```

```swift
let allNines = nums.↓reduce(true, { $0.0 && $0.1 == 9 })
```

```swift
let anyNines = nums.↓reduce(false, { $0.0 || $0.1 == 9 })
```

```swift
let allValid = validators.↓reduce(true, { $0 && $1(input) })
```

```swift
let anyValid = validators.↓reduce(false, { $0 || $1(input) })
```

</details>



## Redundant Discardable Let

Identifier | Enabled by default | Supports autocorrection | Kind | Analyzer | Minimum Swift Compiler Version
Expand Down
1 change: 1 addition & 0 deletions Source/SwiftLintFramework/Models/MasterRuleList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public let masterRuleList = RuleList(rules: [
QuickDiscouragedCallRule.self,
QuickDiscouragedFocusedTestRule.self,
QuickDiscouragedPendingTestRule.self,
ReduceBooleanRule.self,
RedundantDiscardableLetRule.self,
RedundantNilCoalescingRule.self,
RedundantObjcAttributeRule.self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public struct NSObjectPreferIsEqualRule: Rule, ConfigurationProviderRule, Automa

private func areAllArguments(toMethod method: [String: SourceKitRepresentable],
ofType typeName: String) -> Bool {
return method.enclosedVarParameters.reduce(true) { soFar, param -> Bool in
soFar && (param.typeName == typeName)
return method.enclosedVarParameters.allSatisfy { param in
param.typeName == typeName
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import SourceKittenFramework

public struct ReduceBooleanRule: Rule, ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)

public init() {}

public static let description = RuleDescription(
identifier: "reduce_boolean",
name: "Reduce Boolean",
description: "Prefer using `.allSatisfy()` or `.contains()` over `reduce(true)` or `reduce(false)`",
kind: .performance,
minSwiftVersion: .fourDotTwo,
nonTriggeringExamples: [
"nums.reduce(0) { $0.0 + $0.1 }",
"nums.reduce(0.0) { $0.0 + $0.1 }"
],
triggeringExamples: [
"let allNines = nums.↓reduce(true) { $0.0 && $0.1 == 9 }",
"let anyNines = nums.↓reduce(false) { $0.0 || $0.1 == 9 }",
"let allValid = validators.↓reduce(true) { $0 && $1(input) }",
"let anyValid = validators.↓reduce(false) { $0 || $1(input) }",
"let allNines = nums.↓reduce(true, { $0.0 && $0.1 == 9 })",
"let anyNines = nums.↓reduce(false, { $0.0 || $0.1 == 9 })",
"let allValid = validators.↓reduce(true, { $0 && $1(input) })",
"let anyValid = validators.↓reduce(false, { $0 || $1(input) })"
]
)

public func validate(file: File) -> [StyleViolation] {
let pattern = "\\breduce\\((true|false)"
return file
.match(pattern: pattern, with: [.identifier, .keyword])
.map { range in
let reason: String
if file.contents[Range(range, in: file.contents)!].contains("true") {
reason = "Use `allSatisfy` instead"
} else {
reason = "Use `contains` instead"
}

return StyleViolation(
ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location),
reason: reason
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,7 @@ public struct UnneededParenthesesInClosureArgumentRule: ConfigurationProviderRul
}

let parametersTokens = file.syntaxMap.tokens(inByteRange: parametersByteRange)
let parametersAreValid = parametersTokens.reduce(true) { isValid, token in
guard isValid else {
return false
}

let parametersAreValid = parametersTokens.allSatisfy { token in
let kind = SyntaxKind(rawValue: token.type)
if kind == .identifier {
return true
Expand Down
8 changes: 6 additions & 2 deletions SwiftLint.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
4A9A3A3A1DC1D75F00DF5183 /* HTMLReporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A9A3A391DC1D75F00DF5183 /* HTMLReporter.swift */; };
4DB7815E1CAD72BA00BC4723 /* LegacyCGGeometryFunctionsRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DB7815C1CAD690100BC4723 /* LegacyCGGeometryFunctionsRule.swift */; };
4DCB8E7F1CBE494E0070FCF0 /* RegexHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DCB8E7D1CBE43640070FCF0 /* RegexHelpers.swift */; };
4E342B4C2215C793008E4EF8 /* ReduceBooleanRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E342B4A2215C6DF008E4EF8 /* ReduceBooleanRule.swift */; };
57ED827B1CF656E3002B3513 /* JUnitReporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57ED82791CF65183002B3513 /* JUnitReporter.swift */; };
584B0D3A2112BA78002F7E25 /* SonarQubeReporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 584B0D392112BA78002F7E25 /* SonarQubeReporter.swift */; };
584B0D3C2112E8FB002F7E25 /* CannedSonarQubeReporterOutput.json in Resources */ = {isa = PBXBuildFile; fileRef = 584B0D3B2112E8FB002F7E25 /* CannedSonarQubeReporterOutput.json */; };
Expand Down Expand Up @@ -539,6 +540,7 @@
4A9A3A391DC1D75F00DF5183 /* HTMLReporter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTMLReporter.swift; sourceTree = "<group>"; };
4DB7815C1CAD690100BC4723 /* LegacyCGGeometryFunctionsRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LegacyCGGeometryFunctionsRule.swift; sourceTree = "<group>"; };
4DCB8E7D1CBE43640070FCF0 /* RegexHelpers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RegexHelpers.swift; sourceTree = "<group>"; };
4E342B4A2215C6DF008E4EF8 /* ReduceBooleanRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReduceBooleanRule.swift; sourceTree = "<group>"; };
5499CA961A2394B700783309 /* Components.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Components.plist; sourceTree = "<group>"; };
5499CA971A2394B700783309 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
57ED82791CF65183002B3513 /* JUnitReporter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JUnitReporter.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1033,6 +1035,7 @@
D42D2B371E09CC0D00CD7A2E /* FirstWhereRule.swift */,
D414D6AD21D22FF500960935 /* LastWhereRule.swift */,
429644B41FB0A99E00D75128 /* SortedFirstLastRule.swift */,
4E342B4A2215C6DF008E4EF8 /* ReduceBooleanRule.swift */,
);
path = Performance;
sourceTree = "<group>";
Expand Down Expand Up @@ -1762,7 +1765,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which sourcery >/dev/null; then\n make Source/SwiftLintFramework/Models/MasterRuleList.swift\nelse\n echo \"Sourcery not found, install with 'brew install sourcery'\"\nfi";
shellScript = "if which sourcery >/dev/null; then\n make Source/SwiftLintFramework/Models/MasterRuleList.swift\nelse\n echo \"Sourcery not found, install with 'brew install sourcery'\"\nfi\n";
showEnvVarsInLog = 0;
};
6CF24C421FC99616008CB0B1 /* Update Tests/LinuxMain.swift */ = {
Expand All @@ -1779,7 +1782,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which sourcery >/dev/null; then\n make Tests/LinuxMain.swift\nelse\n echo \"Sourcery not found, install with 'brew install sourcery'\"\nfi";
shellScript = "if which sourcery >/dev/null; then\n make Tests/LinuxMain.swift\nelse\n echo \"Sourcery not found, install with 'brew install sourcery'\"\nfi\n";
showEnvVarsInLog = 0;
};
C2265FAB1A4B86AC00158358 /* Check Xcode Version */ = {
Expand Down Expand Up @@ -1871,6 +1874,7 @@
E88198571BEA953300333A11 /* ForceCastRule.swift in Sources */,
D44AD2761C0AA5350048F7B0 /* LegacyConstructorRule.swift in Sources */,
D41985E721F85014003BE2B7 /* NSLocalizedStringKeyRule.swift in Sources */,
4E342B4C2215C793008E4EF8 /* ReduceBooleanRule.swift in Sources */,
D286EC021E02DF6F0003CF72 /* SortedImportsRule.swift in Sources */,
D40E041C1F46E3B30043BC4E /* SuperfluousDisableCommandRule.swift in Sources */,
82F614F42106015100D23904 /* MultilineArgumentsBracketsRule.swift in Sources */,
Expand Down
7 changes: 7 additions & 0 deletions Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,12 @@ extension QuickDiscouragedPendingTestRuleTests {
]
}

extension ReduceBooleanRuleTests {
static var allTests: [(String, (ReduceBooleanRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}

extension RedundantDiscardableLetRuleTests {
static var allTests: [(String, (RedundantDiscardableLetRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
Expand Down Expand Up @@ -1593,6 +1599,7 @@ XCTMain([
testCase(QuickDiscouragedCallRuleTests.allTests),
testCase(QuickDiscouragedFocusedTestRuleTests.allTests),
testCase(QuickDiscouragedPendingTestRuleTests.allTests),
testCase(ReduceBooleanRuleTests.allTests),
testCase(RedundantDiscardableLetRuleTests.allTests),
testCase(RedundantNilCoalescingRuleTests.allTests),
testCase(RedundantObjcAttributeRuleTests.allTests),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,12 @@ class QuickDiscouragedPendingTestRuleTests: XCTestCase {
}
}

class ReduceBooleanRuleTests: XCTestCase {
func testWithDefaultConfiguration() {
verifyRule(ReduceBooleanRule.description)
}
}

class RedundantDiscardableLetRuleTests: XCTestCase {
func testWithDefaultConfiguration() {
verifyRule(RedundantDiscardableLetRule.description)
Expand Down