forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NotificationCenterDetachmentRule.swift
82 lines (67 loc) · 2.98 KB
/
NotificationCenterDetachmentRule.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
//
// NotificationCenterDetachmentRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 01/15/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct NotificationCenterDetachmentRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "notification_center_detachment",
name: "Notification Center Detachment",
description: "An object should only remove itself as an observer in `deinit`.",
kind: .lint,
nonTriggeringExamples: NotificationCenterDetachmentRuleExamples.nonTriggeringExamples,
triggeringExamples: NotificationCenterDetachmentRuleExamples.triggeringExamples
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .class else {
return []
}
return violationOffsets(file: file, dictionary: dictionary).map { offset in
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
}
}
func violationOffsets(file: File, dictionary: [String: SourceKitRepresentable]) -> [Int] {
return dictionary.substructure.flatMap { subDict -> [Int] in
guard let kindString = subDict.kind,
let kind = SwiftExpressionKind(rawValue: kindString) else {
return []
}
// complete detachment is allowed on `deinit`
if kind == .other,
SwiftDeclarationKind(rawValue: kindString) == .functionMethodInstance,
subDict.name == "deinit" {
return []
}
if kind == .call, subDict.name == methodName,
parameterIsSelf(dictionary: subDict, file: file),
let offset = subDict.offset {
return [offset]
}
return violationOffsets(file: file, dictionary: subDict)
}
}
private var methodName = "NotificationCenter.default.removeObserver"
private func parameterIsSelf(dictionary: [String: SourceKitRepresentable], file: File) -> Bool {
guard let bodyOffset = dictionary.bodyOffset,
let bodyLength = dictionary.bodyLength else {
return false
}
let range = NSRange(location: bodyOffset, length: bodyLength)
let tokens = file.syntaxMap.tokens(inByteRange: range)
let types = tokens.flatMap { SyntaxKind(rawValue: $0.type) }
guard types == [.keyword], let token = tokens.first else {
return false
}
let body = file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length)
return body == "self"
}
}