@@ -17,19 +17,21 @@ import SwiftSyntax
1717public class LookupCache {
1818 /// Cached results of `ScopeSyntax.lookupParent` calls.
1919 /// Identified by `SyntaxIdentifier`.
20- private var ancestorResultsCache : [ SyntaxIdentifier : [ LookupResult ] ] = [ : ]
20+ private let ancestorResultsCache : LRUCache < SyntaxIdentifier , [ LookupResult ] >
2121 /// Cached results of `SequentialScopeSyntax.sequentialLookup` calls.
2222 /// Identified by `SyntaxIdentifier`.
23- private var sequentialResultsCache : [ SyntaxIdentifier : [ LookupResult ] ] = [ : ]
23+ private let sequentialResultsCache : LRUCache < SyntaxIdentifier , [ LookupResult ] >
2424 /// Looked-up scope identifiers during cache accesses.
2525 private var hits : Set < SyntaxIdentifier > = [ ]
2626
2727 private let dropMod : Int
2828 private var evictionCount = 0
2929
3030 /// Creates a new unqualified lookup cache.
31+ /// `capacity` describes the maximum amount of entries in the cache.
32+ /// The cache size is maintained according to the LRU (Least Recently Used) policy.
3133 /// `drop` parameter specifies how many eviction calls will be
32- /// ignored before evicting not-hit members of the cache .
34+ /// ignored before evicting not-hit members from subsequent lookups .
3335 ///
3436 /// Example cache eviction sequences (s - skip, e - evict):
3537 /// - `drop = 0` - `e -> e -> e -> e -> e -> ...`
@@ -44,7 +46,9 @@ public class LookupCache {
4446 /// memory accesses could take longer, slowing down the eviction process. That's why the `drop` value
4547 /// could be fine-tuned to maximize the performance given file size,
4648 /// number of lookups, and amount of available memory.
47- public init ( drop: Int = 0 ) {
49+ public init ( capacity: Int , drop: Int = 0 ) {
50+ self . ancestorResultsCache = LRUCache ( capacity: ( capacity + 1 ) / 2 )
51+ self . sequentialResultsCache = LRUCache ( capacity: capacity / 2 )
4852 self . dropMod = drop + 1
4953 }
5054
@@ -91,9 +95,9 @@ public class LookupCache {
9195 guard evictionCount != 0 else { return }
9296 }
9397
94- for key in Set ( ancestorResultsCache. keys ) . union ( sequentialResultsCache. keys ) . subtracting ( hits) {
95- ancestorResultsCache. removeValue ( forKey : key)
96- sequentialResultsCache. removeValue ( forKey : key)
98+ for key in ancestorResultsCache. keysInCache . union ( sequentialResultsCache. keysInCache ) . subtracting ( hits) {
99+ ancestorResultsCache [ key] = nil
100+ sequentialResultsCache [ key] = nil
97101 }
98102
99103 hits = [ ]
0 commit comments