forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNestingRule.swift
71 lines (64 loc) · 3.17 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
//
// NestingRule.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct NestingRule: ASTRule, ConfigurationProviderRule {
public var configuration = NestingConfiguration(typeLevelWarning: 1,
typeLevelError: nil,
statementLevelWarning: 5,
statementLevelError: nil)
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.",
kind: .metrics,
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) A { \(kind) B { ↓\(kind) C {} } }\n"
} + [
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\n↓func func6() {\n}\n}\n}\n}\n}\n}\n}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return validate(file: file, kind: kind, dictionary: dictionary, level: 0)
}
private func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable],
level: Int) -> [StyleViolation] {
var violations = [StyleViolation]()
let typeKinds = SwiftDeclarationKind.typeKinds()
if let offset = dictionary.offset {
let (targetName, targetLevel) = typeKinds.contains(kind)
? ("Types", configuration.typeLevel) : ("Statements", configuration.statementLevel)
if let severity = configuration.severity(with: targetLevel, for: level) {
let threshold = configuration.threshold(with: targetLevel, for: severity)
let pluralSuffix = threshold > 1 ? "s" : ""
violations.append(StyleViolation(
ruleDescription: type(of: self).description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: "\(targetName) should be nested at most \(threshold) level\(pluralSuffix) deep"))
}
}
violations.append(contentsOf: dictionary.substructure.flatMap { subDict in
if let kind = (subDict.kind).flatMap(SwiftDeclarationKind.init) {
return (kind, subDict)
}
return nil
}.flatMap { kind, subDict in
return validate(file: file, kind: kind, dictionary: subDict, level: level + 1)
})
return violations
}
}