forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNestingRule.swift
72 lines (67 loc) · 3.06 KB
/
NestingRule.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// NestingRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct NestingRule: ASTRule {
public init() {}
public static let description = RuleDescription(
identifier: "nesting",
name: "Nesting",
description: "Types should be nested at most 1 level deep, " +
"and statements should be nested at most 5 levels deep.",
nonTriggeringExamples: ["class", "struct", "enum"].flatMap { kind in
["\(kind) Class0 { \(kind) Class1 {} }\n",
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\n}\n}\n}\n}\n}\n}\n"]
} + ["enum Enum0 { enum Enum1 { case Case } }"],
triggeringExamples: ["class", "struct", "enum"].map { kind in
"\(kind) Class0 { \(kind) Class1 { \(kind) Class2 {} } }\n"
} + [
"enum Enum0 { enum Enum1 { enum Enum2 { case Case } } }",
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\nfunc func6() {\n}\n}\n}\n}\n}\n}\n}\n"
]
)
public func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
return validateFile(file, kind: kind, dictionary: dictionary, level: 0)
}
func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary,
level: Int) -> [StyleViolation] {
var violations = [StyleViolation]()
let typeKinds: [SwiftDeclarationKind] = [.Class, .Struct, .Typealias, .Enum]
if let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) {
let location = Location(file: file, offset: offset)
if level > 1 && typeKinds.contains(kind) {
violations.append(StyleViolation(ruleDescription: self.dynamicType.description,
location: location, reason: "Types should be nested at most 1 level deep"))
} else if level > 5 {
violations.append(StyleViolation(ruleDescription: self.dynamicType.description,
location: location,
reason: "Statements should be nested at most 5 levels deep"))
}
}
let substructure = dictionary["key.substructure"] as? XPCArray ?? []
violations.appendContentsOf(substructure.flatMap { subItem in
let subDict = subItem as? XPCDictionary
let kindString = subDict?["key.kind"] as? String
let kind = kindString.flatMap { kindString in
return SwiftDeclarationKind(rawValue: kindString)
}
if let kind = kind, subDict = subDict {
return (kind, subDict)
}
return nil
}.flatMap { (kind, dict) -> [StyleViolation] in
return self.validateFile(file, kind: kind, dictionary: dict, level: level + 1)
})
return violations
}
}