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

Rewrite ExplicitInitRule as ASTRule #826

Merged
merged 4 commits into from
Oct 29, 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
[Marcelo Fabri](https://github.com/marcelofabri)
[#681](https://github.com/realm/SwiftLint/issues/681)

* Add ``ExplicitInitRule`` Opt-In rule to discourage calling ``init``
directly.
[Matt Taube](https://github.com/mtaube)
[#715](https://github.com/realm/SwiftLint/pull/715)

##### Bug Fixes

* Fixed whitespace being added to TODO messages.
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 @@ -50,6 +50,7 @@ public let masterRuleList = RuleList(rules:
CustomRules.self,
CyclomaticComplexityRule.self,
EmptyCountRule.self,
ExplicitInitRule.self,
FileLengthRule.self,
ForceCastRule.self,
ForceTryRule.self,
Expand Down
124 changes: 124 additions & 0 deletions Source/SwiftLintFramework/Rules/ExplicitInitRule.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//
// ExplicitInitRule.swift
// SwiftLint
//
// Created by Matt Taube on 7/2/16.
// Copyright (c) 2016 Realm. All rights reserved.
//

import Foundation
import SourceKittenFramework

public struct ExplicitInitRule: ASTRule, ConfigurationProviderRule, CorrectableRule, OptInRule {

public var configuration = SeverityConfiguration(.Warning)

public init() {}

public static let description = RuleDescription(
identifier: "explicit_init",
name: "Explicit Init",
description: "Explicitly calling .init() should be avoided.",
nonTriggeringExamples: [
"import Foundation; class C: NSObject { override init() { super.init() }}", // super
"struct S { let n: Int }; extension S { init() { self.init(n: 1) } }", // self
"[1].flatMap(String.init)", // pass init as closure
"[String.self].map { $0.init(1) }", // initialize from a metatype value
"[String.self].map { type in type.init(1) }", // initialize from a metatype value
],
triggeringExamples: [
"[1].flatMap{String↓.init($0)}",
"[String.self].map { Type in Type↓.init(1) }", // starting with capital assumes as type
],
corrections: [
"[1].flatMap{String.init($0)}" : "[1].flatMap{String($0)}",
]
)

public enum Kind: String {
case expr_call = "source.lang.swift.expr.call"
case other
public init?(rawValue: String) {
switch rawValue {
case expr_call.rawValue: self = .expr_call
default: self = .other
}
}
}

public func validateFile(
file: File,
kind: ExplicitInitRule.Kind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return violationRangesInFile(file, kind: kind, dictionary: dictionary).map {
StyleViolation(ruleDescription: self.dynamicType.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}

private let initializerWithType = regex("^[A-Z].*\\.init$")

private func violationRangesInFile(
file: File,
kind: ExplicitInitRule.Kind,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {

func isExpected(name: String) -> Bool {
let range = NSRange(location: 0, length: name.utf16.count)
return !["super.init", "self.init"].contains(name)
&& initializerWithType.numberOfMatchesInString(name, options: [], range: range) != 0
}

let length = ".init".utf8.count

guard kind == .expr_call,
let name = dictionary["key.name"] as? String where isExpected(name),
let nameOffset = dictionary["key.nameoffset"] as? Int64,
let nameLength = dictionary["key.namelength"] as? Int64,
let range = (file.contents as NSString)
.byteRangeToNSRange(start: Int(nameOffset + nameLength) - length, length: length)
else { return [] }
return [range]
}

private func violationRangesInFile(
file: File,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
let substructure = dictionary["key.substructure"] as? [SourceKitRepresentable] ?? []
return substructure.flatMap { subItem -> [NSRange] in
guard let subDict = subItem as? [String: SourceKitRepresentable],
kindString = subDict["key.kind"] as? String,
kind = ExplicitInitRule.Kind(rawValue: kindString) else {
return []
}
return violationRangesInFile(file, dictionary: subDict) +
violationRangesInFile(file, kind: kind, dictionary: subDict)
}
}

private func violationRangesInFile(file: File) -> [NSRange] {
return violationRangesInFile(file, dictionary: file.structure.dictionary).sort { lh, rh in
lh.location > rh.location
}
}

public func correctFile(file: File) -> [Correction] {
let matches = violationRangesInFile(file)
.filter { !file.ruleEnabledViolatingRanges([$0], forRule: self).isEmpty }
guard !matches.isEmpty else { return [] }

let description = self.dynamicType.description
var corrections = [Correction]()
var contents = file.contents
for range in matches {
contents = (contents as NSString)
.stringByReplacingCharactersInRange(range, withString: "")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}

file.write(contents)
return corrections
}
}
4 changes: 4 additions & 0 deletions SwiftLint.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
6CCFCF301CFEF742003239EB /* Yaml.framework in Embed Frameworks into SwiftLintFramework.framework */ = {isa = PBXBuildFile; fileRef = E89376AC1B8A701E0025708E /* Yaml.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
7250948A1D0859260039B353 /* StatementPositionConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 725094881D0855760039B353 /* StatementPositionConfiguration.swift */; };
78F032461D7C877E00BE709A /* OverridenSuperCallRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78F032441D7C877800BE709A /* OverridenSuperCallRule.swift */; };
7C0C2E7A1D2866CB0076435A /* ExplicitInitRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C0C2E791D2866CB0076435A /* ExplicitInitRule.swift */; };
78F032481D7D614300BE709A /* OverridenSuperCallConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78F032471D7D614300BE709A /* OverridenSuperCallConfiguration.swift */; };
83894F221B0C928A006214E1 /* RulesCommand.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83894F211B0C928A006214E1 /* RulesCommand.swift */; };
83D71E281B131ECE000395DE /* RuleDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83D71E261B131EB5000395DE /* RuleDescription.swift */; };
Expand Down Expand Up @@ -228,6 +229,7 @@
6CC4259A1C77046200AEA885 /* SyntaxMap+SwiftLint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SyntaxMap+SwiftLint.swift"; sourceTree = "<group>"; };
725094881D0855760039B353 /* StatementPositionConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementPositionConfiguration.swift; sourceTree = "<group>"; };
78F032441D7C877800BE709A /* OverridenSuperCallRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OverridenSuperCallRule.swift; sourceTree = "<group>"; };
7C0C2E791D2866CB0076435A /* ExplicitInitRule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExplicitInitRule.swift; sourceTree = "<group>"; };
78F032471D7D614300BE709A /* OverridenSuperCallConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OverridenSuperCallConfiguration.swift; sourceTree = "<group>"; };
83894F211B0C928A006214E1 /* RulesCommand.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RulesCommand.swift; sourceTree = "<group>"; };
83D71E261B131EB5000395DE /* RuleDescription.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RuleDescription.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -614,6 +616,7 @@
3B1DF0111C5148140011BCED /* CustomRules.swift */,
2E02005E1C54BF680024D09D /* CyclomaticComplexityRule.swift */,
E847F0A81BFBBABD00EA9363 /* EmptyCountRule.swift */,
7C0C2E791D2866CB0076435A /* ExplicitInitRule.swift */,
E88DEA891B0992B300A66CB0 /* FileLengthRule.swift */,
E88DEA7F1B09903300A66CB0 /* ForceCastRule.swift */,
E816194D1BFBFEAB00946723 /* ForceTryRule.swift */,
Expand Down Expand Up @@ -964,6 +967,7 @@
D47A510E1DB29EEB00A4CC21 /* SwitchCaseOnNewlineRule.swift in Sources */,
E88DEA6F1B09843F00A66CB0 /* Location.swift in Sources */,
93E0C3CE1D67BD7F007FA25D /* ConditionalReturnsOnNewline.swift in Sources */,
7C0C2E7A1D2866CB0076435A /* ExplicitInitRule.swift in Sources */,
E88DEA771B098D0C00A66CB0 /* Rule.swift in Sources */,
24B4DF0D1D6DFDE90097803B /* RedundantNilCoalesingRule.swift in Sources */,
7250948A1D0859260039B353 /* StatementPositionConfiguration.swift in Sources */,
Expand Down
4 changes: 4 additions & 0 deletions Tests/SwiftLintFramework/RulesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ class RulesTests: XCTestCase {
verifyRule(EmptyCountRule.description)
}

func testExplicitInit() {
verifyRule(ExplicitInitRule.description)
}

func testFileLength() {
verifyRule(FileLengthRule.description, commentDoesntViolate: false)
}
Expand Down