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

Fix explicit_type_interface when used in statements or in capture groups #2321

Closed
wants to merge 1 commit into from
Closed
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 @@ -52,6 +52,10 @@

#### Bug Fixes

* Fix `explicit_type_interface` when used in statements.
[Daniel Metzing](https://github.com/dirtydanee)
[#2154](https://github.com/realm/SwiftLint/issues/2154)

* Fix an issue with `control_statement` where commas in clauses prevented the
rule from applying.
[Allen Wu](https://github.com/allewun)
Expand Down
90 changes: 70 additions & 20 deletions Source/SwiftLintFramework/Rules/ExplicitTypeInterfaceRule.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
import Foundation
import SourceKittenFramework

public struct ExplicitTypeInterfaceRule: ASTRule, OptInRule, ConfigurationProviderRule {
public struct ExplicitTypeInterfaceRule: OptInRule, ConfigurationProviderRule {

public var configuration = ExplicitTypeInterfaceConfiguration()

public init() {}

fileprivate static let captureGroupPattern =
"\\{" + // The { character
"\\s*" + // Zero or more whitespace character(s)
"\\[" + // The [ character
"(" + // Start if the first capturing group
"\\s*" + // Zero or more whitespace character(s)
"\\w+" + // At least one word character
"\\s+" + // At least one whitespace character
"\\w+" + // At least one world character
",*" + // Zero or more , character
")" + // End of the first capturing group
"+" + // At least occurance of the first capturing group
"\\]" // The ] character

public static let description = RuleDescription(
identifier: "explicit_type_interface",
name: "Explicit Type Interface",
Expand All @@ -27,37 +42,72 @@ public struct ExplicitTypeInterfaceRule: ASTRule, OptInRule, ConfigurationProvid
]
)

public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
public func validate(file: File) -> [StyleViolation] {

let captureGroupByteRanges = file.captureGroupByteRanges
let declarationRanges = file.declarationRanges(of: [.guard, .case])

let collector = NamespaceCollector(dictionary: file.structure.dictionary)
let elements = collector.findAllElements(of: [.varClass, .varLocal, .varGlobal, .varStatic, .varInstance])

return elements.compactMap { element -> StyleViolation? in
guard configuration.allowedKinds.contains(element.kind),
!element.dictionary.containsType,
(!configuration.allowRedundancy || !element.dictionary.isInitCall(file: file)),
!captureGroupByteRanges.contains(where: { $0.contains(element.offset) }),
!declarationRanges.contains(where: { $0.contains(element.offset) }) else {
return nil
}

return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: element.offset))
}
}
}

private extension File {
var captureGroupByteRanges: [NSRange] {
return match(pattern: ExplicitTypeInterfaceRule.captureGroupPattern,
excludingSyntaxKinds: SyntaxKind.commentKinds)
.compactMap { contents.bridge().NSRangeToByteRange(start: $0.location, length: $0.length) }
}

guard configuration.allowedKinds.contains(kind),
!containsType(dictionary: dictionary),
(!configuration.allowRedundancy || !assigneeIsInitCall(file: file, dictionary: dictionary)),
let offset = dictionary.offset else {
return []
func declarationRanges(of statements: [StatementKind]) -> [NSRange] {
var ranges: [NSRange] = []
func search(in dictionary: [String: SourceKitRepresentable]) {
if let kind = dictionary.kind,
let statement = StatementKind(rawValue: kind),
statements.contains(statement),
let statementOffset = dictionary.offset,
let statementLength = dictionary.length {
ranges.append(NSRange(location: statementOffset, length: statementLength))
}

dictionary.substructure.forEach(search)
}

return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: offset))
]
search(in: structure.dictionary)
return ranges
}
}

private func containsType(dictionary: [String: SourceKitRepresentable]) -> Bool {
return dictionary.typeName != nil
private extension Dictionary where Key == String, Value == SourceKitRepresentable {
var containsType: Bool {
return typeName != nil
}

private func assigneeIsInitCall(file: File, dictionary: [String: SourceKitRepresentable]) -> Bool {
func isInitCall(file: File) -> Bool {
guard
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let afterNameRange = file.contents.bridge().byteRangeToNSRange(start: nameOffset + nameLength, length: 0)
let nameOffset = nameOffset,
let nameLength = nameLength,
case let contents = file.contents.bridge(),
let afterNameRange = contents.byteRangeToNSRange(start: nameOffset + nameLength, length: 0)
else {
return false
}

let contentAfterName = file.contents.bridge().substring(from: afterNameRange.location)
let contentAfterName = contents.substring(from: afterNameRange.location)
let initCallRegex = regex("^\\s*=\\s*\\p{Lu}[^\\(\\s<]*(?:<[^\\>]*>)?\\(")

return initCallRegex.firstMatch(in: contentAfterName, options: [], range: contentAfterName.fullNSRange) != nil
Expand Down
4 changes: 3 additions & 1 deletion Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,9 @@ extension ExplicitTypeInterfaceRuleTests {
("testExplicitTypeInterface", testExplicitTypeInterface),
("testExcludeLocalVars", testExcludeLocalVars),
("testExcludeClassVars", testExcludeClassVars),
("testAllowRedundancy", testAllowRedundancy)
("testAllowRedundancy", testAllowRedundancy),
("testEmbededInStatements", testEmbededInStatements),
("testCaptureGroup", testCaptureGroup)
]
}

Expand Down
48 changes: 48 additions & 0 deletions Tests/SwiftLintFrameworkTests/ExplicitTypeInterfaceRuleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,58 @@ class ExplicitTypeInterfaceRuleTests: XCTestCase {
"class Foo {\n ↓static var myStaticVar = 0\n}\n",
"class Foo {\n ↓class var myClassVar = 0\n}\n"
]

let description = ExplicitTypeInterfaceRule.description
.with(triggeringExamples: triggeringExamples)
.with(nonTriggeringExamples: nonTriggeringExamples)

verifyRule(description, ruleConfiguration: ["allow_redundancy": true])
}

func testEmbededInStatements() {
let nonTriggeringExamples = [
"var foo: String?\n guard let strongFoo = foo else { return }",
"struct SomeError: Error {}\n" +
"var error: Error?\n" +
"switch error {\n" +
"case let error as SomeError:\n" +
" break\n" +
"default:\n" +
" break\n" +
"}"
]
let triggeringExamples = ExplicitTypeInterfaceRule.description.triggeringExamples
let description = ExplicitTypeInterfaceRule.description
.with(triggeringExamples: triggeringExamples)
.with(nonTriggeringExamples: nonTriggeringExamples)

verifyRule(description)
}

func testCaptureGroup() {
let nonTriggeringExamples = [
"var k: Int = 0\n" +
"_ = { [weak k] in\n" +
" print(k)\n" +
" }",
"var k: Int = 0\n" +
"_ = { [unowned k] in\n" +
" print(k)\n" +
" }",
"class Foo {\n" +
" func bar() {\n" +
" var k: Int = 0\n" +
" _ = { [weak self, weak k] in\n" +
" guard let strongSelf = self else { return }\n" +
" }\n" +
" }\n" +
"}"
]
let triggeringExamples = ExplicitTypeInterfaceRule.description.triggeringExamples
let description = ExplicitTypeInterfaceRule.description
.with(triggeringExamples: triggeringExamples)
.with(nonTriggeringExamples: nonTriggeringExamples)

verifyRule(description)
}
}