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 UnusedPrivateDeclarationRule #2385

Merged
merged 2 commits into from
Sep 6, 2018
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
11 changes: 7 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
e.g. `--compiler-log-path /path/to/xcodebuild.log`
[JP Simard](https://github.com/jpsim)

* Add a new opt-in `explicit_self` analyzer rule to enforce the use of explicit
references to `self.` when accessing instance variables or functions.
* Add an `explicit_self` analyzer rule to enforce the use of explicit references
to `self.` when accessing instance variables or functions.
[JP Simard](https://github.com/jpsim)

* Add a new opt-in `unused_import` analyzer rule to lint for unnecessary
imports.
* Add an `unused_import` analyzer rule to lint for unnecessary imports.
[JP Simard](https://github.com/jpsim)

* Add an `unused_private_declaration` analyzer rule to lint for unused private
declarations.
[JP Simard](https://github.com/jpsim)

#### Enhancements
Expand Down
31 changes: 31 additions & 0 deletions Rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
* [Unused Enumerated](#unused-enumerated)
* [Unused Import](#unused-import)
* [Unused Optional Binding](#unused-optional-binding)
* [Unused Private Declaration](#unused-private-declaration)
* [Valid IBInspectable](#valid-ibinspectable)
* [Vertical Parameter Alignment](#vertical-parameter-alignment)
* [Vertical Parameter Alignment On Call](#vertical-parameter-alignment-on-call)
Expand Down Expand Up @@ -20165,6 +20166,36 @@ if case .some(let ↓_) = self {}



## Unused Private Declaration

Identifier | Enabled by default | Supports autocorrection | Kind | Analyzer | Minimum Swift Compiler Version
--- | --- | --- | --- | --- | ---
`unused_private_declaration` | Disabled | No | lint | Yes | 3.0.0

Private declarations should be referenced in that file.

### Examples

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

```swift
private let kConstant = 0
_ = kConstant
```

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

```swift
private let ↓kConstant = 0
```

</details>



## Valid IBInspectable

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 @@ -139,6 +139,7 @@ public let masterRuleList = RuleList(rules: [
UnusedEnumeratedRule.self,
UnusedImportRule.self,
UnusedOptionalBindingRule.self,
UnusedPrivateDeclarationRule.self,
ValidIBInspectableRule.self,
VerticalParameterAlignmentOnCallRule.self,
VerticalParameterAlignmentRule.self,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import Foundation
import SourceKittenFramework

public struct UnusedPrivateDeclarationRule: ConfigurationProviderRule, AnalyzerRule {
public var configuration = SeverityConfiguration(.warning)

public init() {}

public static let description = RuleDescription(
identifier: "unused_private_declaration",
name: "Unused Private Declaration",
description: "Private declarations should be referenced in that file.",
kind: .lint,
nonTriggeringExamples: [
"""
private let kConstant = 0
_ = kConstant
"""
],
triggeringExamples: [
"""
private let ↓kConstant = 0
"""
],
requiresFileOnDisk: true
)

public func validate(file: File, compilerArguments: [String]) -> [StyleViolation] {
return violationOffsets(in: file, compilerArguments: compilerArguments).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}

private func violationOffsets(in file: File, compilerArguments: [String]) -> [Int] {
guard !compilerArguments.isEmpty else {
queuedPrintError("""
Attempted to lint file at path '\(file.path ?? "...")' with the \
\(type(of: self).description.identifier) rule without any compiler arguments.
""")
return []
}

let allCursorInfo = file.allCursorInfo(compilerArguments: compilerArguments)
let privateDeclarationUSRs = File.declaredUSRs(allCursorInfo: allCursorInfo, acls: [.private, .fileprivate])
let referencedUSRs = File.referencedUSRs(allCursorInfo: allCursorInfo)
let unusedPrivateDeclarations = privateDeclarationUSRs.filter { !referencedUSRs.contains($0.usr) }
return unusedPrivateDeclarations.map { $0.nameOffset }
}
}

// MARK: - File Extensions

private extension File {
func allCursorInfo(compilerArguments: [String]) -> [[String: SourceKitRepresentable]] {
guard let path = path, let editorOpen = try? Request.editorOpen(file: self).send() else {
return []
}

return syntaxMap.tokens.compactMap { token in
let offset = Int64(token.offset)
var cursorInfo = try? Request.cursorInfo(file: path, offset: offset,
arguments: compilerArguments).send()
if let acl = File.aclAtOffset(offset, substructureElement: editorOpen) {
cursorInfo?["key.accessibility"] = acl
}
cursorInfo?["swiftlint.offset"] = offset
return cursorInfo
}
}

static func declaredUSRs(allCursorInfo: [[String: SourceKitRepresentable]],
acls: [AccessControlLevel]) -> [(usr: String, nameOffset: Int)] {
return allCursorInfo.compactMap { declaredUSRAndOffset(cursorInfo: $0, acls: acls) }
}

static func referencedUSRs(allCursorInfo: [[String: SourceKitRepresentable]]) -> [String] {
return allCursorInfo.compactMap(referencedUSR)
}

private static func declaredUSRAndOffset(cursorInfo: [String: SourceKitRepresentable],
acls: [AccessControlLevel]) -> (usr: String, nameOffset: Int)? {
if let offset = cursorInfo["swiftlint.offset"] as? Int64,
let usr = cursorInfo["key.usr"] as? String,
let kind = (cursorInfo["key.kind"] as? String).flatMap(SwiftDeclarationKind.init(rawValue:)),
!declarationKindsToSkip.contains(kind),
let acl = (cursorInfo["key.accessibility"] as? String).flatMap(AccessControlLevel.init(rawValue:)),
acls.contains(acl) {
// Skip declarations marked as @IBOutlet, @IBAction or @objc
// since those might not be referenced in code, but only dynamically (e.g. Interface Builder)
if let annotatedDecl = cursorInfo["key.annotated_decl"] as? String,
["@IBOutlet", "@IBAction", "@objc"].contains(where: annotatedDecl.contains) {
return nil
}
// Skip declarations that override another. This works for both subclass overrides &
// protocol extension overrides.
if cursorInfo["key.overrides"] != nil {
return nil
}
return (usr, Int(offset))
}

return nil
}

private static func referencedUSR(cursorInfo: [String: SourceKitRepresentable]) -> String? {
if let usr = cursorInfo["key.usr"] as? String,
let kind = cursorInfo["key.kind"] as? String,
kind.contains("source.lang.swift.ref") {
return usr
}

return nil
}

private static func aclAtOffset(_ offset: Int64, substructureElement: [String: SourceKitRepresentable]) -> String? {
if let nameOffset = substructureElement["key.nameoffset"] as? Int64,
nameOffset == offset,
let acl = substructureElement["key.accessibility"] as? String {
return acl
}
if let substructure = substructureElement[SwiftDocKey.substructure.rawValue] as? [SourceKitRepresentable] {
let nestedSubstructure = substructure.compactMap({ $0 as? [String: SourceKitRepresentable] })
for child in nestedSubstructure {
if let acl = File.aclAtOffset(offset, substructureElement: child) {
return acl
}
}
}
return nil
}
}

// Skip initializers, enum cases and subscripts since we can't reliably detect if they're used.
private let declarationKindsToSkip: Set<SwiftDeclarationKind> = [
.functionConstructor,
.enumelement,
.functionSubscript
]
4 changes: 4 additions & 0 deletions SwiftLint.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@
8F2CC1CD20A6A189006ED34F /* FileNameRuleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F2CC1CC20A6A189006ED34F /* FileNameRuleTests.swift */; };
8F6AA75B211905B8009BA28A /* LintableFilesVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F6AA75A211905B8009BA28A /* LintableFilesVisitor.swift */; };
8F6AA75D21190830009BA28A /* CompilerArgumentsExtractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F6AA75C21190830009BA28A /* CompilerArgumentsExtractor.swift */; };
8F6B3154213CDCD100858E44 /* UnusedPrivateDeclarationRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F6B3153213CDCD100858E44 /* UnusedPrivateDeclarationRule.swift */; };
8F715B83213B528B00427BD9 /* UnusedImportRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F715B82213B528B00427BD9 /* UnusedImportRule.swift */; };
8F8050821FFE0CBB006F5B93 /* Configuration+IndentationStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F8050811FFE0CBB006F5B93 /* Configuration+IndentationStyle.swift */; };
8FC8523B2117BDDE0015269B /* ExplicitSelfRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC8523A2117BDDE0015269B /* ExplicitSelfRule.swift */; };
Expand Down Expand Up @@ -559,6 +560,7 @@
8F2CC1CC20A6A189006ED34F /* FileNameRuleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileNameRuleTests.swift; sourceTree = "<group>"; };
8F6AA75A211905B8009BA28A /* LintableFilesVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LintableFilesVisitor.swift; sourceTree = "<group>"; };
8F6AA75C21190830009BA28A /* CompilerArgumentsExtractor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompilerArgumentsExtractor.swift; sourceTree = "<group>"; };
8F6B3153213CDCD100858E44 /* UnusedPrivateDeclarationRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UnusedPrivateDeclarationRule.swift; sourceTree = "<group>"; };
8F715B82213B528B00427BD9 /* UnusedImportRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnusedImportRule.swift; sourceTree = "<group>"; };
8F8050811FFE0CBB006F5B93 /* Configuration+IndentationStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Configuration+IndentationStyle.swift"; sourceTree = "<group>"; };
8FC8523A2117BDDE0015269B /* ExplicitSelfRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExplicitSelfRule.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -987,6 +989,7 @@
E88DEA811B0990A700A66CB0 /* TodoRule.swift */,
D40AD0891E032F9700F48C30 /* UnusedClosureParameterRule.swift */,
8F715B82213B528B00427BD9 /* UnusedImportRule.swift */,
8F6B3153213CDCD100858E44 /* UnusedPrivateDeclarationRule.swift */,
D442541E1DB87C3D00492EA4 /* ValidIBInspectableRule.swift */,
094384FF1D5D2382009168CF /* WeakDelegateRule.swift */,
1872906F1FC37A9B0016BEA2 /* YodaConditionRule.swift */,
Expand Down Expand Up @@ -1750,6 +1753,7 @@
E86623671F1D377900AAA3A2 /* Configuration+Parsing.swift in Sources */,
3BCC04CD1C4F5694006073C3 /* ConfigurationError.swift in Sources */,
D4C4A34E1DEA877200E0E04C /* FileHeaderRule.swift in Sources */,
8F6B3154213CDCD100858E44 /* UnusedPrivateDeclarationRule.swift in Sources */,
1894D746207D585400BD94CF /* SwiftDeclarationAttributeKind+Swiftlint.swift in Sources */,
6250D32A1ED4DFEB00735129 /* MultilineParametersRule.swift in Sources */,
009E092A1DFEE4DD00B588A7 /* ProhibitedSuperConfiguration.swift in Sources */,
Expand Down
3 changes: 2 additions & 1 deletion Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,8 @@ extension RulesTests {
("testLeadingWhitespace", testLeadingWhitespace),
("testMark", testMark),
("testRequiredEnumCase", testRequiredEnumCase),
("testTrailingNewline", testTrailingNewline)
("testTrailingNewline", testTrailingNewline),
("testUnusedPrivateDeclaration", testUnusedPrivateDeclaration)
]
}

Expand Down
10 changes: 10 additions & 0 deletions Tests/SwiftLintFrameworkTests/RulesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ class RulesTests: XCTestCase {
verifyRule(TrailingNewlineRule.description, commentDoesntViolate: false,
stringDoesntViolate: false)
}

// Remove and make UnusedPrivateDeclarationRule conform to AutomaticTestableRule
// when CircleCI updates its Xcode 10 image to the GM release.
func testUnusedPrivateDeclaration() {
#if swift(>=4.1.50) && !SWIFT_PACKAGE
print("\(#function) is failing with Xcode 10 on CirclCI")
#else
verifyRule(UnusedPrivateDeclarationRule.description)
#endif
}
}