|
| 1 | +//===--- Fingerprint.swift -------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +@_spi(RawSyntax) |
| 14 | +import SwiftSyntax |
| 15 | +import SwiftIfConfig |
| 16 | + |
| 17 | +struct Fingerprint: Equatable { |
| 18 | + typealias Core = (UInt64, UInt64) |
| 19 | + var core: Core |
| 20 | + init(core: Core) { |
| 21 | + self.core = core |
| 22 | + } |
| 23 | + |
| 24 | + static func == (lhs: Self, rhs: Self) -> Bool { |
| 25 | + return lhs.core == rhs.core |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +extension StableHasher { |
| 30 | + @inline(__always) |
| 31 | + mutating func combine(text: SyntaxText) { |
| 32 | + let buffer = UnsafeRawBufferPointer( |
| 33 | + start: UnsafeRawPointer(text.baseAddress), |
| 34 | + count: text.count |
| 35 | + ) |
| 36 | + self.combine(UInt(truncatingIfNeeded: buffer.count)) |
| 37 | + self.combine(bytes: buffer) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +final class FingerprintVisitor: SyntaxVisitor { |
| 42 | + let configuredRegions: ConfiguredRegions |
| 43 | + var hasher: StableHasher |
| 44 | + |
| 45 | + init(configuredRegions: ConfiguredRegions) { |
| 46 | + self.configuredRegions = configuredRegions |
| 47 | + self.hasher = StableHasher() |
| 48 | + super.init(viewMode: .sourceAccurate) |
| 49 | + } |
| 50 | + |
| 51 | + func finalize() -> Fingerprint { |
| 52 | + Fingerprint(core: hasher.finalize()) |
| 53 | + } |
| 54 | + |
| 55 | + override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { |
| 56 | + // Collect all token texts. |
| 57 | + hasher.combine(text: token.rawText) |
| 58 | + return .skipChildren |
| 59 | + } |
| 60 | + |
| 61 | + override func visit(_ node: MemberBlockSyntax) -> SyntaxVisitorContinueKind { |
| 62 | + // Skip nominal decl / extension member blocks. |
| 63 | + return .skipChildren |
| 64 | + } |
| 65 | + |
| 66 | + override func visit(_ node: CodeBlockSyntax) -> SyntaxVisitorContinueKind { |
| 67 | + // Skip function bodies. |
| 68 | + // FIXME: Don't skip closure bodies or other control flow statement blocks. |
| 69 | + // E.g. 'var val = { if condition { "foo" } else { "bar" } }()' |
| 70 | + return .skipChildren |
| 71 | + } |
| 72 | + |
| 73 | + override func visit(_ node: IfConfigDeclSyntax) -> SyntaxVisitorContinueKind { |
| 74 | + if let active = configuredRegions.activeClause(for: node) { |
| 75 | + self.walk(active) |
| 76 | + } |
| 77 | + return .skipChildren |
| 78 | + } |
| 79 | +} |
0 commit comments