-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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 unused_capture_list rule #2719
Merged
marcelofabri
merged 5 commits into
realm:master
from
daltonclaybrook:dc-unused-capture-list-rule
Apr 15, 2019
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d8f671c
WIP - create unused capture list rule
daltonclaybrook 0a0a60b
Rule is now passing tests
daltonclaybrook 41c8da2
Cleanup
daltonclaybrook 665920a
Fix line length violation + updated changelog
daltonclaybrook 5999012
PR feedback updates
daltonclaybrook File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
142 changes: 142 additions & 0 deletions
142
Source/SwiftLintFramework/Rules/Lint/UnusedCaptureListRule.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
import Foundation | ||
import SourceKittenFramework | ||
|
||
public struct UnusedCaptureListRule: ASTRule, ConfigurationProviderRule, AutomaticTestableRule { | ||
public var configuration = SeverityConfiguration(.warning) | ||
|
||
public init() {} | ||
|
||
public static var description = RuleDescription( | ||
identifier: "unused_capture_list", | ||
name: "Unused Capture List", | ||
description: "Unused reference in a capture list should be removed.", | ||
kind: .lint, | ||
minSwiftVersion: .fourDotTwo, | ||
nonTriggeringExamples: [ | ||
""" | ||
[1, 2].map { [weak self] num in | ||
self?.handle(num) | ||
} | ||
""", | ||
""" | ||
let failure: Failure = { [weak self, unowned delegate = self.delegate!] foo in | ||
delegate.handle(foo, self) | ||
} | ||
""", | ||
""" | ||
numbers.forEach({ | ||
[weak handler] in | ||
handler?.handle($0) | ||
}) | ||
""", | ||
"{ [foo] in foo.bar() }()", | ||
"sizes.max().flatMap { [(offset: offset, size: $0)] } ?? []" | ||
], | ||
triggeringExamples: [ | ||
""" | ||
[1, 2].map { [↓weak self] num in | ||
print(num) | ||
} | ||
""", | ||
""" | ||
let failure: Failure = { [weak self, ↓unowned delegate = self.delegate!] foo in | ||
self?.handle(foo) | ||
} | ||
""", | ||
""" | ||
let failure: Failure = { [↓weak self, ↓unowned delegate = self.delegate!] foo in | ||
print(foo) | ||
} | ||
""", | ||
""" | ||
numbers.forEach({ | ||
[weak handler] in | ||
print($0) | ||
}) | ||
""", | ||
"{ [↓foo] in _ }()" | ||
] | ||
) | ||
|
||
private let captureListRegex = regex("^\\{\\s*\\[([^\\]]+)\\].*\\bin\\b") | ||
|
||
public func validate(file: File, kind: SwiftExpressionKind, | ||
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { | ||
let contents = file.contents.bridge() | ||
guard kind == .closure, | ||
let offset = dictionary.offset, | ||
let length = dictionary.length, | ||
let closureRange = contents.byteRangeToNSRange(start: offset, length: length), | ||
let match = captureListRegex.firstMatch(in: file.contents, options: [], range: closureRange) | ||
else { return [] } | ||
|
||
let captureListRange = match.range(at: 1) | ||
guard captureListRange.location != NSNotFound, | ||
captureListRange.length > 0 else { return [] } | ||
|
||
let captureList = contents.substring(with: captureListRange) | ||
let references = referencesAndLocationsFromCaptureList(captureList) | ||
|
||
let restOfClosureLocation = captureListRange.location + captureListRange.length + 1 | ||
let restOfClosureLength = closureRange.length - (restOfClosureLocation - closureRange.location) | ||
let restOfClosureRange = NSRange(location: restOfClosureLocation, length: restOfClosureLength) | ||
guard let restOfClosureByteRange = contents | ||
.NSRangeToByteRange(start: restOfClosureRange.location, length: restOfClosureRange.length) | ||
else { return [] } | ||
|
||
let identifiers = identifierStrings(in: file, byteRange: restOfClosureByteRange) | ||
return violations(in: file, references: references, | ||
identifiers: identifiers, captureListRange: captureListRange) | ||
} | ||
|
||
// MARK: - Private | ||
|
||
private func referencesAndLocationsFromCaptureList(_ captureList: String) -> [(String, Int)] { | ||
var locationOffset = 0 | ||
return captureList.components(separatedBy: ",") | ||
.reduce(into: [(String, Int)]()) { referencesAndLocations, item in | ||
let item = item.bridge() | ||
let range = item.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted) | ||
guard range.location != NSNotFound else { return } | ||
|
||
let location = range.location + locationOffset | ||
locationOffset += item.length + 1 // 1 for comma | ||
let reference = item.components(separatedBy: "=") | ||
.first? | ||
.trimmingCharacters(in: .whitespacesAndNewlines) | ||
.components(separatedBy: .whitespaces) | ||
.last | ||
if let reference = reference { | ||
referencesAndLocations.append((reference, location)) | ||
} | ||
} | ||
} | ||
|
||
private func identifierStrings(in file: File, byteRange: NSRange) -> Set<String> { | ||
let contents = file.contents.bridge() | ||
let identifiers = file.syntaxMap | ||
.tokens(inByteRange: byteRange) | ||
.compactMap { token -> String? in | ||
guard token.type == SyntaxKind.identifier.rawValue || token.type == SyntaxKind.keyword.rawValue, | ||
let range = contents.byteRangeToNSRange(start: token.offset, length: token.length) | ||
else { return nil } | ||
return contents.substring(with: range) | ||
} | ||
return Set(identifiers) | ||
} | ||
|
||
private func violations(in file: File, references: [(String, Int)], | ||
identifiers: Set<String>, captureListRange: NSRange) -> [StyleViolation] { | ||
return references.compactMap { reference, location -> StyleViolation? in | ||
guard !identifiers.contains(reference) else { return nil } | ||
let offset = captureListRange.location + location | ||
let reason = "Unused reference \(reference) in a capture list should be removed." | ||
return StyleViolation( | ||
ruleDescription: type(of: self).description, | ||
severity: configuration.severity, | ||
location: Location(file: file, characterOffset: offset), | ||
reason: reason | ||
) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you add
swiftVersion: .fourDotTwo
?SwiftSyntaxKind.closure
is only returned by SourceKit in 4.2+