forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OverriddenSuperCallRule.swift
87 lines (80 loc) · 3.37 KB
/
OverriddenSuperCallRule.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
// OverriddenSuperCallRule.swift
// SwiftLint
//
// Created by Angel Garcia on 04/09/16.
// Copyright © 2016 Realm. All rights reserved.
//
import SourceKittenFramework
public struct OverriddenSuperCallRule: ConfigurationProviderRule, ASTRule, OptInRule {
public var configuration = OverridenSuperCallConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "overridden_super_call",
name: "Overridden methods call super",
description: "Some overridden methods should always call super",
nonTriggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {\n" +
"\t\tself.method1()\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t\tself.method2()\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func loadView() {\n" +
"\t}\n" +
"}\n",
"class Some {\n" +
"\tfunc viewWillAppear(_ animated: Bool) {\n" +
"\t}\n" +
"}\n"
],
triggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) ↓{\n" +
"\t\t//Not calling to super\n" +
"\t\tself.method()\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) ↓{\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t\t//Other code\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func didReceiveMemoryWarning() ↓{\n" +
"\t}\n" +
"}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard let offset = dictionary.bodyOffset,
let name = dictionary.name,
kind == .functionMethodInstance,
configuration.resolvedMethodNames.contains(name),
dictionary.enclosedSwiftAttributes.contains("source.decl.attribute.override")
else { return [] }
let callsToSuper = dictionary.extractCallsToSuper(methodName: name)
if callsToSuper.isEmpty {
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: "Method '\(name)' should call to super function")]
} else if callsToSuper.count > 1 {
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: "Method '\(name)' should call to super only once")]
}
return []
}
}