import Foundation import HelderCore public protocol SymbolServicing: Sendable { /// Every declared PHP class-like name; decides which tokens ⌘-click may underline. func names() async -> Set /// Declarations of `name` plus every reference, grouped by file. func lookup(_ name: String) async -> SymbolLookup /// Drops the index after a file change; the next caller rebuilds it. func invalidate() async } /// Ripgrep-backed, with the same walk fallback as search when ripgrep is missing. public actor SymbolService: SymbolServicing { public nonisolated let root: URL private let runner: ProcessRunning private let config: ConfigServicing private let locator: ExecutableLocator private let environment: [String: String] private var index: [String: [SymbolDef]]? private var building: Task<[String: [SymbolDef]], Never>? /// Bumped by `invalidate()`, so a build that started before a file change is not cached. private var generation = 0 /// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path. public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .standard, environment: [String: String] = ProcessInfo.processInfo.environment) { self.root = root self.config = config self.runner = runner self.locator = locator self.environment = environment } /// Builds lazily on first use; concurrent callers share one build. Two ripgrep passes over /// `*.php` (vendor included): `PHPSymbols.declarationPattern`, then `traitUsePattern`, where /// a trait belongs to the nearest declaration above it in the same file. public func names() async -> Set { Set(await currentIndex().keys) } /// Word-regexp ripgrep over `*.php` without vendor; drops import lines and the declaration /// lines themselves; caps at `SymbolLimits.maxReferenceFiles` files. Non-identifiers return empty. public func lookup(_ name: String) async -> SymbolLookup { guard PHPSymbols.isIdentifier(name) else { return .empty(name) } let definitions = PHPSymbols.sortDefinitions(await currentIndex()[name] ?? []) let declared = Set(definitions.map { "\($0.path):\($0.line)" }) let query = LineQuery(pattern: .word(name), fileExtension: "php") let matches = await scanner.matches(query, filter: await filter(base: IgnoreRules.symbolReferenceIgnore)) var groups: [RefGroup] = [] var groupIndex: [String: Int] = [:] var count = 0 for match in matches { let path = RipgrepJSON.relativePath(match.path, root: root.path) if declared.contains("\(path):\(match.line)") || PHPSymbols.isImportLine(match.text) { continue } let hit = Self.hit(match) if let i = groupIndex[path] { groups[i].hits.append(hit) } else { guard groups.count < SymbolLimits.maxReferenceFiles else { continue } groupIndex[path] = groups.count groups.append(RefGroup(path: path, hits: [hit])) } count += 1 } return SymbolLookup(name: name, definitions: definitions, references: groups, referenceCount: count) } public func invalidate() async { index = nil building = nil generation += 1 } private func currentIndex() async -> [String: [SymbolDef]] { if let index { return index } if let building { return await building.value } let started = generation let task = Task { await self.build() } building = task let built = await task.value if generation == started { index = built building = nil } return built } private func build() async -> [String: [SymbolDef]] { let started = Date() let filter = await filter(base: IgnoreRules.symbolDeclarationIgnore) let scanner = self.scanner var defs: [SymbolDef] = [] var defsByFile: [String: [Int]] = [:] var namespaces: [String: String] = [:] // A file's matches arrive together and in line order, and `namespace` precedes the // declarations it covers, so the last namespace seen is the right one. let declarations = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php"), filter: filter) for match in declarations { let path = RipgrepJSON.relativePath(match.path, root: root.path) if let namespace = PHPSymbols.parseNamespace(match.text) { namespaces[path] = namespace continue } guard let parsed = PHPSymbols.parseDeclaration(match.text) else { continue } defsByFile[path, default: []].append(defs.count) defs.append(SymbolDef(name: parsed.name, path: path, line: match.line, kind: parsed.kind, namespace: namespaces[path] ?? "", parents: parsed.parents, interfaces: parsed.interfaces)) } let traitUses = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.traitUsePattern), fileExtension: "php"), filter: filter) for match in traitUses { let traits = PHPSymbols.parseTraitUse(match.text) let path = RipgrepJSON.relativePath(match.path, root: root.path) let candidates = (defsByFile[path] ?? []).filter { defs[$0].line < match.line } guard !traits.isEmpty, let owner = candidates.max(by: { defs[$0].line < defs[$1].line }) else { continue } for trait in traits where !defs[owner].traits.contains(trait) { defs[owner].traits.append(trait) } } let byName = Dictionary(grouping: defs, by: \.name) Log.info("symbols", "index built: \(byName.count) classes in \(Int(Date().timeIntervalSince(started) * 1000)) ms") return byName } private var scanner: ProjectScanning { ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment) } private func filter(base: [String]) async -> ScanFilter { ScanFilter(base: base, files: await config.current().files) } /// A reference hit; ripgrep's byte offset becomes a UTF-16 offset clamped to the capped line. private static func hit(_ match: RipgrepMatch) -> ContentHit { let text = String(match.text.prefix(SymbolLimits.maxLineLength)) let bytes = Array(match.text.utf8.prefix(match.byteOffset)) let offset = String(decoding: bytes, as: UTF8.self).utf16.count return ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count)) } }