Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add First where rule #1012

Merged
merged 5 commits into from
Dec 22, 2016
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
1 change: 1 addition & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ opt_in_rules:
- attributes
- operator_usage_whitespace
- closure_end_indentation
- first_where

file_header:
required_pattern: |
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@
[Marcelo Fabri](https://github.com/marcelofabri)
[#603](https://github.com/realm/SwiftLint/issues/603)

* Add `first_where` opt-in rule that warns against using
`.filter { /* ... */ }.first` in collections, as
`.first(where: { /* ... */ })` is often more efficient.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops, bad rebase 😅

[Marcelo Fabri](https://github.com/marcelofabri)
[#1005](https://github.com/realm/SwiftLint/issues/1005)

##### Bug Fixes

* `FunctionParameterCountRule` also ignores generic initializers.
Expand Down
4 changes: 2 additions & 2 deletions Source/SwiftLintFramework/Extensions/File+SwiftLint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,9 @@ extension File {
let fileRegions = regions()
if fileRegions.isEmpty { return violatingRanges }
let violatingRanges = violatingRanges.filter { range in
let region = fileRegions.filter {
let region = fileRegions.first(where: {
$0.contains(Location(file: self, characterOffset: range.location))
}.first
})
return region?.isRuleEnabled(rule) ?? true
}
return violatingRanges
Expand Down
4 changes: 2 additions & 2 deletions Source/SwiftLintFramework/Models/Linter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public struct Linter {
ruleTimes.append((id, -start.timeIntervalSinceNow))
}
return violations.filter { violation in
guard let violationRegion = regions.filter({ $0.contains(violation.location) })
.first else {
guard let violationRegion = regions
.first(where: { $0.contains(violation.location) }) else {
return true
}
return violationRegion.isRuleEnabled(rule)
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 @@ -59,6 +59,7 @@ public let masterRuleList = RuleList(rules:
ExplicitInitRule.self,
FileHeaderRule.self,
FileLengthRule.self,
FirstWhereRule.self,
ForceCastRule.self,
ForceTryRule.self,
ForceUnwrappingRule.self,
Expand Down
97 changes: 97 additions & 0 deletions Source/SwiftLintFramework/Rules/FirstWhereRule.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//
// FirstWhereRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/20/16.
// Copyright © 2016 Realm. All rights reserved.
//

import Foundation
import SourceKittenFramework

public struct FirstWhereRule: OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)

public init() {}

public static let description = RuleDescription(
identifier: "first_where",
name: "First Where",
description: "Prefer using `.first(where:)` over `.filter { }.first` in collections.",
nonTriggeringExamples: [
"kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier\n",
"myList.first(where: { $0 % 2 == 0 })\n",
"matchPattern(pattern).filter { $0.first == .identifier }\n"
],
triggeringExamples: [
"↓myList.filter { $0 % 2 == 0 }.first\n",
"↓myList.filter({ $0 % 2 == 0 }).first\n",
"↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first\n",
"↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first?.something()\n",
"↓myList.filter(someFunction).first\n"
]
)

public func validateFile(_ file: File) -> [StyleViolation] {
let pattern = "[\\s\\}\\)]*\\.first"
let firstRanges = file.matchPattern(pattern, withSyntaxKinds: [.identifier])
let contents = file.contents.bridge()
let structure = file.structure

let violatingLocations: [Int] = firstRanges.flatMap {
guard let bodyByteRange = contents.NSRangeToByteRange(start: $0.location,
length: $0.length),
case let firstLocation = $0.location + $0.length - 1,
let firstByteRange = contents.NSRangeToByteRange(start: firstLocation,
length: 1) else {
return nil
}

return methodCallFor(bodyByteRange.location - 1,
excludingOffset: firstByteRange.location,
dictionary: structure.dictionary, predicate: { dictionary in
guard let name = dictionary["key.name"] as? String else {
return false
}

return name.hasSuffix(".filter")
})
}

return violatingLocations.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}

private func methodCallFor(_ byteOffset: Int,
excludingOffset: Int,
dictionary: [String: SourceKitRepresentable],
predicate: ([String: SourceKitRepresentable]) -> Bool) -> Int? {

if let kindString = (dictionary["key.kind"] as? String),
SwiftExpressionKind(rawValue: kindString) == .call,
let bodyOffset = (dictionary["key.bodyoffset"] as? Int64).flatMap({ Int($0) }),
let bodyLength = (dictionary["key.bodylength"] as? Int64).flatMap({ Int($0) }),
let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) {
let byteRange = NSRange(location: bodyOffset, length: bodyLength)

if NSLocationInRange(byteOffset, byteRange) &&
!NSLocationInRange(excludingOffset, byteRange) && predicate(dictionary) {
return offset
}
}

if let subStructure = dictionary["key.substructure"] as? [SourceKitRepresentable] {
for case let dictionary as [String: SourceKitRepresentable] in subStructure {
if let offset = methodCallFor(byteOffset, excludingOffset: excludingOffset,
dictionary: dictionary, predicate: predicate) {
return offset
}
}
}

return nil
}
}
57 changes: 29 additions & 28 deletions Source/SwiftLintFramework/Rules/TodoRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,38 +47,39 @@ public struct TodoRule: ConfigurationProviderRule {
]
)

fileprivate func customMessage(_ lines: [Line], location: Location) -> String {
var reason = type(of: self).description.description
private func customMessage(_ lines: [Line], location: Location) -> String {
var reason = type(of: self).description.description

guard let lineIndex = location.line,
let currentLine = lines.filter({ $0.index == lineIndex }).first
else { return reason }
guard let lineIndex = location.line,
let currentLine = lines.first(where: { $0.index == lineIndex }) else {
return reason
}

// customizing the reason message to be specific to fixme or todo
var message = currentLine.content
if currentLine.content.contains("FIXME") {
reason = "FIXMEs should be avoided"
message = message.replacingOccurrences(of: "FIXME", with: "")
} else {
reason = "TODOs should be avoided"
message = message.replacingOccurrences(of: "TODO", with: "")
}
message = message.replacingOccurrences(of: "//", with: "")
// trim whitespace
message = message.trimmingCharacters(in: .whitespacesAndNewlines)
// customizing the reason message to be specific to fixme or todo
var message = currentLine.content
if currentLine.content.contains("FIXME") {
reason = "FIXMEs should be avoided"
message = message.replacingOccurrences(of: "FIXME", with: "")
} else {
reason = "TODOs should be avoided"
message = message.replacingOccurrences(of: "TODO", with: "")
}
message = message.replacingOccurrences(of: "//", with: "")
// trim whitespace
message = message.trimmingCharacters(in: .whitespacesAndNewlines)

// limiting the output length of todo message
let maxLengthOfMessage = 30
if message.utf16.count > maxLengthOfMessage {
let index = message.index(message.startIndex,
offsetBy: maxLengthOfMessage,
limitedBy: message.endIndex) ?? message.endIndex
reason += message.substring(to: index) + "..."
} else {
reason += message
}
// limiting the output length of todo message
let maxLengthOfMessage = 30
if message.utf16.count > maxLengthOfMessage {
let index = message.index(message.startIndex,
offsetBy: maxLengthOfMessage,
limitedBy: message.endIndex) ?? message.endIndex
reason += message.substring(to: index) + "..."
} else {
reason += message
}

return reason
return reason
}

public func validateFile(_ file: File) -> [StyleViolation] {
Expand Down
4 changes: 4 additions & 0 deletions SwiftLint.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
D40AD08A1E032F9700F48C30 /* UnusedClosureParameterRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = D40AD0891E032F9700F48C30 /* UnusedClosureParameterRule.swift */; };
D40F83881DE9179200524C62 /* TrailingCommaConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = D40F83871DE9179200524C62 /* TrailingCommaConfiguration.swift */; };
D41E7E0B1DF9DABB0065259A /* RedundantStringEnumValueRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = D41E7E0A1DF9DABB0065259A /* RedundantStringEnumValueRule.swift */; };
D42D2B381E09CC0D00CD7A2E /* FirstWhereRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = D42D2B371E09CC0D00CD7A2E /* FirstWhereRule.swift */; };
D4348EEA1C46122C007707FB /* FunctionBodyLengthRuleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4348EE91C46122C007707FB /* FunctionBodyLengthRuleTests.swift */; };
D43B04641E0620AB004016AF /* UnusedEnumeratedRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = D43B04631E0620AB004016AF /* UnusedEnumeratedRule.swift */; };
D43B046B1E075905004016AF /* ClosureEndIndentationRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = D43B046A1E075905004016AF /* ClosureEndIndentationRule.swift */; };
Expand Down Expand Up @@ -323,6 +324,7 @@
D40AD0891E032F9700F48C30 /* UnusedClosureParameterRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UnusedClosureParameterRule.swift; sourceTree = "<group>"; };
D40F83871DE9179200524C62 /* TrailingCommaConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TrailingCommaConfiguration.swift; sourceTree = "<group>"; };
D41E7E0A1DF9DABB0065259A /* RedundantStringEnumValueRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RedundantStringEnumValueRule.swift; sourceTree = "<group>"; };
D42D2B371E09CC0D00CD7A2E /* FirstWhereRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FirstWhereRule.swift; sourceTree = "<group>"; };
D4348EE91C46122C007707FB /* FunctionBodyLengthRuleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionBodyLengthRuleTests.swift; sourceTree = "<group>"; };
D43B04631E0620AB004016AF /* UnusedEnumeratedRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UnusedEnumeratedRule.swift; sourceTree = "<group>"; };
D43B046A1E075905004016AF /* ClosureEndIndentationRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ClosureEndIndentationRule.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -729,6 +731,7 @@
7C0C2E791D2866CB0076435A /* ExplicitInitRule.swift */,
D4C4A34D1DEA877200E0E04C /* FileHeaderRule.swift */,
E88DEA891B0992B300A66CB0 /* FileLengthRule.swift */,
D42D2B371E09CC0D00CD7A2E /* FirstWhereRule.swift */,
E88DEA7F1B09903300A66CB0 /* ForceCastRule.swift */,
E816194D1BFBFEAB00946723 /* ForceTryRule.swift */,
B58AEED51C492C7B00E901FD /* ForceUnwrappingRule.swift */,
Expand Down Expand Up @@ -1087,6 +1090,7 @@
E847F0A91BFBBABD00EA9363 /* EmptyCountRule.swift in Sources */,
D46252541DF63FB200BE2CA1 /* NumberSeparatorRule.swift in Sources */,
E315B83C1DFA4BC500621B44 /* DynamicInlineRule.swift in Sources */,
D42D2B381E09CC0D00CD7A2E /* FirstWhereRule.swift in Sources */,
D44254271DB9C15C00492EA4 /* SyntacticSugarRule.swift in Sources */,
E88198441BEA93D200333A11 /* ColonRule.swift in Sources */,
E809EDA11B8A71DF00399043 /* Configuration.swift in Sources */,
Expand Down
5 changes: 5 additions & 0 deletions Tests/SwiftLintFrameworkTests/RulesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ class RulesTests: XCTestCase {
testMultiByteOffsets: false)
}

func testFirstWhere() {
verifyRule(FirstWhereRule.description)
}

func testForceCast() {
verifyRule(ForceCastRule.description)
}
Expand Down Expand Up @@ -356,6 +360,7 @@ extension RulesTests {
("testEmptyParenthesesWithTrailingClosure", testEmptyParenthesesWithTrailingClosure),
("testExplicitInit", testExplicitInit),
("testFileLength", testFileLength),
("testFirstWhere", testFirstWhere),
("testForceCast", testForceCast),
("testForceTry", testForceTry),
// ("testForceUnwrapping", testForceUnwrapping),
Expand Down