Skip to content

Commit

Permalink
Migrate to Swift 3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
norio-nomura committed Oct 8, 2016
1 parent e92503a commit 8bf15f1
Show file tree
Hide file tree
Showing 94 changed files with 821 additions and 797 deletions.
2 changes: 1 addition & 1 deletion Source/SwiftLintFramework/Extensions/Array+SwiftLint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import Foundation

extension Array {
static func arrayOf(obj: AnyObject?) -> [Element]? {
static func arrayOf(_ obj: Any?) -> [Element]? {
if let array = obj as? [Element] {
return array
} else if let obj = obj as? Element {
Expand Down
33 changes: 16 additions & 17 deletions Source/SwiftLintFramework/Extensions/File+Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ private var queueForRebuild = [Structure]()

private struct Cache<T> {

private var values = [String: T]()
private var factory: File -> T
fileprivate var values = [String: T]()
fileprivate var factory: (File) -> T

private init(_ factory: File -> T) {
fileprivate init(_ factory: @escaping (File) -> T) {
self.factory = factory
}

private mutating func get(file: File) -> T {
fileprivate mutating func get(_ file: File) -> T {
let key = file.cacheKey
if let value = values[key] {
return value
Expand All @@ -54,20 +54,20 @@ private struct Cache<T> {
return value
}

private mutating func invalidate(file: File) {
fileprivate mutating func invalidate(_ file: File) {
if let key = file.path {
values.removeValueForKey(key)
values.removeValue(forKey: key)
}
}

private mutating func clear() {
values.removeAll(keepCapacity: false)
fileprivate mutating func clear() {
values.removeAll(keepingCapacity: false)
}
}

extension File {

private var cacheKey: String {
fileprivate var cacheKey: String {
return path ?? "\(ObjectIdentifier(self).hashValue)"
}

Expand All @@ -77,9 +77,9 @@ extension File {
}
set {
if newValue {
responseCache.values[cacheKey] = Optional<[String: SourceKitRepresentable]>.None
responseCache.values[cacheKey] = Optional<[String: SourceKitRepresentable]>.none
} else {
responseCache.values.removeValueForKey(cacheKey)
responseCache.values.removeValue(forKey: cacheKey)
}
}
}
Expand Down Expand Up @@ -128,7 +128,7 @@ extension File {

public func invalidateCache() {
responseCache.invalidate(self)
assertHandlers.removeValueForKey(cacheKey)
assertHandlers.removeValue(forKey: cacheKey)
structureCache.invalidate(self)
syntaxMapCache.invalidate(self)
syntaxKindsByLinesCache.invalidate(self)
Expand All @@ -152,15 +152,15 @@ extension File {
}
}

private func dictFromKeyValuePairs<Key: Hashable, Value>(pairs: [(Key, Value)]) -> [Key: Value] {
private func dictFromKeyValuePairs<Key: Hashable, Value>(_ pairs: [(Key, Value)]) -> [Key: Value] {
var dict = [Key: Value]()
for pair in pairs {
dict[pair.0] = pair.1
}
return dict
}

private func substructureForDict(dict: [String: SourceKitRepresentable]) ->
private func substructureForDict(_ dict: [String: SourceKitRepresentable]) ->
[[String: SourceKitRepresentable]]? {
return (dict["key.substructure"] as? [SourceKitRepresentable])?.flatMap {
$0 as? [String: SourceKitRepresentable]
Expand All @@ -170,9 +170,8 @@ private func substructureForDict(dict: [String: SourceKitRepresentable]) ->
private func rebuildAllDeclarationsByType() {
let allDeclarationsByType = queueForRebuild.flatMap { structure -> (String, [String])? in
guard let firstSubstructureDict = substructureForDict(structure.dictionary)?.first,
name = firstSubstructureDict["key.name"] as? String,
kind = (firstSubstructureDict["key.kind"] as? String).flatMap(SwiftDeclarationKind.init)
where kind == .Protocol,
let name = firstSubstructureDict["key.name"] as? String,
let kind = (firstSubstructureDict["key.kind"] as? String).flatMap(SwiftDeclarationKind.init), kind == .Protocol,
let substructure = substructureForDict(firstSubstructureDict) else {
return nil
}
Expand Down
62 changes: 33 additions & 29 deletions Source/SwiftLintFramework/Extensions/File+SwiftLint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import Foundation
import SourceKittenFramework

internal func regex(pattern: String) -> NSRegularExpression {
internal func regex(_ pattern: String) -> NSRegularExpression {
// all patterns used for regular expressions in SwiftLint are string literals which have been
// confirmed to work, so it's ok to force-try here.

Expand All @@ -35,7 +35,7 @@ extension File {
return regions
}

private func commands() -> [Command] {
fileprivate func commands() -> [Command] {
if sourcekitdFailed {
return []
}
Expand All @@ -48,15 +48,15 @@ extension File {
}
}

private func endOfNextCommand(nextCommand: Command?) -> Location {
fileprivate func endOfNextCommand(_ nextCommand: Command?) -> Location {
guard let nextCommand = nextCommand else {
return Location(file: path, line: Int.max, character: Int.max)
}
let nextLine: Int
let nextCharacter: Int?
if let nextCommandCharacter = nextCommand.character {
nextLine = nextCommand.line
if nextCommand.character > 0 {
if nextCommand.character! > 0 {
nextCharacter = nextCommandCharacter - 1
} else {
nextCharacter = nil
Expand All @@ -68,36 +68,36 @@ extension File {
return Location(file: path, line: nextLine, character: nextCharacter)
}

internal func matchPattern(pattern: String,
internal func matchPattern(_ pattern: String,
withSyntaxKinds syntaxKinds: [SyntaxKind]) -> [NSRange] {
return matchPattern(pattern).filter { _, kindsInRange in
return kindsInRange.count == syntaxKinds.count &&
zip(kindsInRange, syntaxKinds).filter({ $0.0 != $0.1 }).isEmpty
}.map { $0.0 }
}

internal func rangesAndTokensMatching(pattern: String) -> [(NSRange, [SyntaxToken])] {
internal func rangesAndTokensMatching(_ pattern: String) -> [(NSRange, [SyntaxToken])] {
return rangesAndTokensMatching(regex(pattern))
}

internal func rangesAndTokensMatching(regex: NSRegularExpression) ->
internal func rangesAndTokensMatching(_ regex: NSRegularExpression) ->
[(NSRange, [SyntaxToken])] {
let contents = self.contents as NSString
let range = NSRange(location: 0, length: contents.length)
let syntax = syntaxMap
return regex.matchesInString(self.contents, options: [], range: range).map { match in
return regex.matches(in: self.contents, options: [], range: range).map { match in
let matchByteRange = contents.NSRangeToByteRange(start: match.range.location,
length: match.range.length) ?? match.range
let tokensInRange = syntax.tokensIn(matchByteRange)
return (match.range, tokensInRange)
}
}

internal func matchPattern(pattern: String) -> [(NSRange, [SyntaxKind])] {
internal func matchPattern(_ pattern: String) -> [(NSRange, [SyntaxKind])] {
return matchPattern(regex(pattern))
}

internal func matchPattern(regex: NSRegularExpression) -> [(NSRange, [SyntaxKind])] {
internal func matchPattern(_ regex: NSRegularExpression) -> [(NSRange, [SyntaxKind])] {
return rangesAndTokensMatching(regex).map { range, tokens in
(range, tokens.flatMap { SyntaxKind(rawValue: $0.type) })
}
Expand All @@ -107,12 +107,12 @@ extension File {
if sourcekitdFailed {
return nil
}
var results = [[SyntaxKind]](count: lines.count + 1, repeatedValue: [])
var tokenGenerator = syntaxMap.tokens.generate()
var lineGenerator = lines.generate()
var results = [[SyntaxKind]](repeating: [], count: lines.count + 1)
var tokenGenerator = syntaxMap.tokens.makeIterator()
var lineGenerator = lines.makeIterator()
var maybeLine = lineGenerator.next()
var maybeToken = tokenGenerator.next()
while let line = maybeLine, token = maybeToken {
while let line = maybeLine, let token = maybeToken {
let tokenRange = NSRange(location: token.offset, length: token.length)
if NSLocationInRange(token.offset, line.byteRange) ||
NSLocationInRange(line.byteRange.location, tokenRange) {
Expand Down Expand Up @@ -144,14 +144,14 @@ extension File {
- returns: An array of [NSRange] objects consisting of regex matches inside
file contents.
*/
internal func matchPattern(pattern: String,
internal func matchPattern(_ pattern: String,
excludingSyntaxKinds syntaxKinds: [SyntaxKind]) -> [NSRange] {
return matchPattern(pattern).filter {
$0.1.filter(syntaxKinds.contains).isEmpty
}.map { $0.0 }
}

internal func matchPattern(pattern: String,
internal func matchPattern(_ pattern: String,
excludingSyntaxKinds: [SyntaxKind],
excludingPattern: String) -> [NSRange] {
let contents = self.contents as NSString
Expand All @@ -160,53 +160,57 @@ extension File {
if matches.isEmpty {
return []
}
let exclusionRanges = regex(excludingPattern).matchesInString(self.contents,
let exclusionRanges = regex(excludingPattern).matches(in: self.contents,
options: [],
range: range)
.ranges()
return matches.filter { !$0.intersectsRanges(exclusionRanges) }
}

internal func validateVariableName(dictionary: [String: SourceKitRepresentable],
internal func validateVariableName(_ dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> (name: String, offset: Int)? {
guard let name = dictionary["key.name"] as? String,
offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) where
let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) ,
SwiftDeclarationKind.variableKinds().contains(kind) && !name.hasPrefix("$") else {
return nil
}
return (name.nameStrippingLeadingUnderscoreIfPrivate(dictionary), offset)
}

internal func append(string: String) {
guard let stringData = string.dataUsingEncoding(NSUTF8StringEncoding) else {
internal func append(_ string: String) {
guard let stringData = string.data(using: .utf8) else {
fatalError("can't encode '\(string)' with UTF8")
}
guard let path = path, fileHandle = NSFileHandle(forWritingAtPath: path) else {
guard let path = path, let fileHandle = FileHandle(forWritingAtPath: path) else {
fatalError("can't write to path '\(self.path)'")
}
fileHandle.seekToEndOfFile()
fileHandle.writeData(stringData)
fileHandle.write(stringData)
fileHandle.closeFile()
contents += string
lines = contents.lines()
}

internal func write(string: String) {
internal func write(_ string: String) {
guard string != contents else {
return
}
guard let path = path else {
fatalError("file needs a path to call write(_:)")
}
guard let stringData = string.dataUsingEncoding(NSUTF8StringEncoding) else {
guard let stringData = string.data(using: .utf8) else {
fatalError("can't encode '\(string)' with UTF8")
}
stringData.writeToFile(path, atomically: true)
do {
try stringData.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
fatalError("can't write file to \(path)")
}
contents = string
lines = contents.lines()
}

internal func ruleEnabledViolatingRanges(violatingRanges: [NSRange],
internal func ruleEnabledViolatingRanges(_ violatingRanges: [NSRange],
forRule rule: Rule) -> [NSRange] {
let fileRegions = regions()
let violatingRanges = violatingRanges.filter { range in
Expand All @@ -218,14 +222,14 @@ extension File {
return violatingRanges
}

private func numberOfCommentAndWhitespaceOnlyLines(startLine: Int, endLine: Int) -> Int {
fileprivate func numberOfCommentAndWhitespaceOnlyLines(_ startLine: Int, endLine: Int) -> Int {
let commentKinds = Set(SyntaxKind.commentKinds())
return syntaxKindsByLines[startLine...endLine].filter { kinds in
kinds.filter { !commentKinds.contains($0) }.isEmpty
}.count
}

internal func exceedsLineCountExcludingCommentsAndWhitespace(start: Int, _ end: Int,
internal func exceedsLineCountExcludingCommentsAndWhitespace(_ start: Int, _ end: Int,
_ limit: Int) -> (Bool, Int) {
if end - start <= limit {
return (false, end - start)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@

import Foundation

extension NSFileManager {
internal func filesToLintAtPath(path: String, rootDirectory: String? = nil) -> [String] {
let rootPath = rootDirectory ?? NSFileManager.defaultManager().currentDirectoryPath
extension FileManager {
internal func filesToLintAtPath(_ path: String, rootDirectory: String? = nil) -> [String] {
let rootPath = rootDirectory ?? FileManager.default.currentDirectoryPath
let absolutePath = (path.absolutePathRepresentation(rootPath) as NSString)
.stringByStandardizingPath
.standardizingPath
var isDirectory: ObjCBool = false
guard fileExistsAtPath(absolutePath, isDirectory: &isDirectory) else {
guard fileExists(atPath: absolutePath, isDirectory: &isDirectory) else {
return []
}
if isDirectory {
if isDirectory.boolValue {
do {
return try subpathsOfDirectoryAtPath(absolutePath)
.map((absolutePath as NSString).stringByAppendingPathComponent).filter {
return try subpathsOfDirectory(atPath: absolutePath)
.map((absolutePath as NSString).appendingPathComponent).filter {
$0.isSwiftFile()
}
} catch {
Expand Down
4 changes: 2 additions & 2 deletions Source/SwiftLintFramework/Extensions/NSRange+SwiftLint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
import Foundation

extension NSRange {
func intersectsRange(range: NSRange) -> Bool {
func intersectsRange(_ range: NSRange) -> Bool {
return NSIntersectionRange(self, range).length > 0
}

func intersectsRanges(ranges: [NSRange]) -> Bool {
func intersectsRanges(_ ranges: [NSRange]) -> Bool {
for range in ranges where intersectsRange(range) {
return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import Foundation
private var regexCache = [String: NSRegularExpression]()

extension NSRegularExpression {
internal static func cached(pattern pattern: String) throws -> NSRegularExpression {
internal static func cached(pattern: String) throws -> NSRegularExpression {
if let result = regexCache[pattern] {
return result
}

let result = try NSRegularExpression(pattern: pattern,
options: [.AnchorsMatchLines, .DotMatchesLineSeparators])
options: [.anchorsMatchLines, .dotMatchesLineSeparators])
regexCache[pattern] = result
return result
}
internal static func forcePattern(pattern: String) -> NSRegularExpression {
internal static func forcePattern(_ pattern: String) -> NSRegularExpression {
// swiftlint:disable:next force_try
return try! .cached(pattern: pattern)
}
Expand Down
Loading

0 comments on commit 8bf15f1

Please sign in to comment.