-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathSwiftLintFile+Cache.swift
More file actions
246 lines (214 loc) · 7.96 KB
/
SwiftLintFile+Cache.swift
File metadata and controls
246 lines (214 loc) · 7.96 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#if canImport(Darwin)
import Darwin
#endif
import Foundation
import SourceKittenFramework
import SwiftDiagnostics
import SwiftIDEUtils
import SwiftOperators
import SwiftParser
import SwiftParserDiagnostics
import SwiftSyntax
private typealias FileCacheKey = UUID
private let responseCache = Cache { file -> [String: any SourceKitRepresentable]? in
do {
return try Request.editorOpen(file: file.file).sendIfNotDisabled()
} catch let error as Request.Error {
queuedPrintError(error.description)
return nil
} catch {
return nil
}
}
private let structureDictionaryCache = Cache { file in
responseCache.get(file).map(Structure.init).map { SourceKittenDictionary($0.dictionary) }
}
private let syntaxTreeCache = Cache { file -> SourceFileSyntax in
Parser.parse(source: file.contents)
}
private let foldedSyntaxTreeCache = Cache { file -> SourceFileSyntax? in
OperatorTable.standardOperators
.foldAll(file.syntaxTree) { _ in /* Don't handle errors. */ }
.as(SourceFileSyntax.self)
}
private let locationConverterCache = Cache { file -> SourceLocationConverter in
SourceLocationConverter(fileName: file.path?.filepath ?? "<nopath>", tree: file.syntaxTree)
}
private let commandsCache = Cache { file -> [Command] in
guard file.contents.contains("swiftlint:") else {
return []
}
return CommandVisitor(locationConverter: file.locationConverter)
.walk(file: file, handler: \.commands)
}
private let syntaxMapCache = Cache { file in
responseCache.get(file).map { SwiftLintSyntaxMap(value: SyntaxMap(sourceKitResponse: $0)) }
}
private let syntaxClassificationsCache = Cache { $0.syntaxTree.classifications }
private let linesWithTokensCache = Cache { $0.computeLinesWithTokens() }
private let swiftSyntaxTokensCache = Cache { file -> [SwiftLintSyntaxToken]? in
// Use SwiftSyntaxKindBridge to derive SourceKitten-compatible tokens from SwiftSyntax
SwiftSyntaxKindBridge.sourceKittenSyntaxKinds(for: file)
}
private let commentLinesCache = Cache { CommentLinesVisitor.commentLines(in: $0) }
private let emptyLinesCache = Cache { EmptyLinesVisitor.emptyLines(in: $0) }
package typealias AssertHandler = () -> Void
// Re-enable once all parser diagnostics in tests have been addressed.
// https://github.com/realm/SwiftLint/issues/3348
@TaskLocal package var parserDiagnosticsDisabledForTests = false
private let assertHandlerCache = Cache { (_: SwiftLintFile) -> AssertHandler? in nil }
private final class Cache<T>: Sendable {
nonisolated(unsafe) private var values = [FileCacheKey: T]()
private let factory: @Sendable (SwiftLintFile) -> T
private let lock = PlatformLock()
fileprivate init(_ factory: @escaping @Sendable (SwiftLintFile) -> T) {
self.factory = factory
}
fileprivate func get(_ file: SwiftLintFile) -> T {
let key = file.cacheKey
return lock.doLocked {
if let cachedValue = values[key] {
return cachedValue
}
let value = factory(file)
values[key] = value
return value
}
}
fileprivate func invalidate(_ file: SwiftLintFile) {
lock.doLocked { values.removeValue(forKey: file.cacheKey) }
}
fileprivate func clear() {
lock.doLocked { values.removeAll(keepingCapacity: false) }
}
fileprivate func set(key: FileCacheKey, value: T) {
lock.doLocked { values[key] = value }
}
fileprivate func unset(key: FileCacheKey) {
lock.doLocked { values.removeValue(forKey: key) }
}
}
extension SwiftLintFile {
fileprivate var cacheKey: FileCacheKey {
id
}
public var sourcekitdFailed: Bool {
get {
responseCache.get(self) == nil
}
set {
if newValue {
responseCache.set(key: cacheKey, value: nil)
} else {
responseCache.unset(key: cacheKey)
}
}
}
package var assertHandler: AssertHandler? {
get {
assertHandlerCache.get(self)
}
set {
assertHandlerCache.set(key: cacheKey, value: newValue)
}
}
public var parserDiagnostics: [String] {
if parserDiagnosticsDisabledForTests {
return []
}
return ParseDiagnosticsGenerator.diagnostics(for: syntaxTree)
.filter { $0.diagMessage.severity == .error }
.map(\.message)
}
public var linesWithTokens: Set<Int> { linesWithTokensCache.get(self) }
public var structureDictionary: SourceKittenDictionary {
guard let structureDictionary = structureDictionaryCache.get(self) else {
if let handler = assertHandler {
handler()
return SourceKittenDictionary([:])
}
queuedFatalError("Never call this for file that sourcekitd fails.")
}
return structureDictionary
}
public var syntaxClassifications: SyntaxClassifications { syntaxClassificationsCache.get(self) }
public var syntaxMap: SwiftLintSyntaxMap {
guard let syntaxMap = syntaxMapCache.get(self) else {
if let handler = assertHandler {
handler()
return SwiftLintSyntaxMap(value: SyntaxMap(data: []))
}
queuedFatalError("Never call this for file that sourcekitd fails.")
}
return syntaxMap
}
public var syntaxTree: SourceFileSyntax { syntaxTreeCache.get(self) }
public var foldedSyntaxTree: SourceFileSyntax? { foldedSyntaxTreeCache.get(self) }
public var locationConverter: SourceLocationConverter { locationConverterCache.get(self) }
public var commands: [Command] { commandsCache.get(self).filter(\.isValid) }
public var invalidCommands: [Command] { commandsCache.get(self).filter { !$0.isValid } }
public var swiftSyntaxDerivedSourceKittenTokens: [SwiftLintSyntaxToken]? {
swiftSyntaxTokensCache.get(self)
}
public var commentLines: Set<Int> { commentLinesCache.get(self) }
public var emptyLines: Set<Int> { emptyLinesCache.get(self) }
/// Invalidates all cached data for this file.
public func invalidateCache() {
if !isVirtual {
file.clearCaches()
}
responseCache.invalidate(self)
assertHandlerCache.invalidate(self)
structureDictionaryCache.invalidate(self)
syntaxClassificationsCache.invalidate(self)
syntaxMapCache.invalidate(self)
swiftSyntaxTokensCache.invalidate(self)
syntaxTreeCache.invalidate(self)
foldedSyntaxTreeCache.invalidate(self)
locationConverterCache.invalidate(self)
commandsCache.invalidate(self)
linesWithTokensCache.invalidate(self)
commentLinesCache.invalidate(self)
emptyLinesCache.invalidate(self)
}
package static func clearCaches() {
responseCache.clear()
assertHandlerCache.clear()
structureDictionaryCache.clear()
syntaxClassificationsCache.clear()
syntaxMapCache.clear()
swiftSyntaxTokensCache.clear()
syntaxTreeCache.clear()
foldedSyntaxTreeCache.clear()
locationConverterCache.clear()
commandsCache.clear()
linesWithTokensCache.clear()
commentLinesCache.clear()
emptyLinesCache.clear()
}
}
private final class PlatformLock: Sendable {
#if canImport(Darwin)
nonisolated(unsafe) private let primitiveLock: UnsafeMutablePointer<os_unfair_lock>
#else
private let primitiveLock = NSLock()
#endif
init() {
#if canImport(Darwin)
primitiveLock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
primitiveLock.initialize(to: os_unfair_lock())
#endif
}
@discardableResult
func doLocked<U>(_ closure: () -> U) -> U {
#if canImport(Darwin)
os_unfair_lock_lock(primitiveLock)
defer { os_unfair_lock_unlock(primitiveLock) }
return closure()
#else
primitiveLock.lock()
defer { primitiveLock.unlock() }
return closure()
#endif
}
}