332 lines · 13.4 KBRaw
| 1 | import type { CodeChange, CodeEdge, CodeGraph, CodeSymbol, CodeSymbolKind } from "@refs/backend/contract"; |
| 2 | |
| 3 | /** A block on the map: `root`, a folder (`dir:path`), a file (`file:path`) or a symbol (its own id). */ |
| 4 | export type NodeId = string; |
| 5 | export type NodeKind = "project" | "folder" | "file" | CodeSymbolKind; |
| 6 | export type DiffStatus = "added" | "changed" | "reaches" | "none"; |
| 7 | |
| 8 | export interface LineDiff { |
| 9 | readonly added: number; |
| 10 | readonly removed: number; |
| 11 | } |
| 12 | |
| 13 | /** One line of a code card: a head line, a removed line, or a fold that stands for unchanged lines. */ |
| 14 | export type CardLine = |
| 15 | | { readonly kind: "line"; readonly number: number; readonly text: string; readonly added: boolean } |
| 16 | | { readonly kind: "removed"; readonly text: string } |
| 17 | | { readonly kind: "fold"; readonly count: number }; |
| 18 | |
| 19 | const ROOT = "root"; |
| 20 | const FOLD_CONTEXT = 2; |
| 21 | const NO_DIFF: LineDiff = { added: 0, removed: 0 }; |
| 22 | |
| 23 | /** |
| 24 | * The code map of one commit, as blocks inside blocks: folders, files, declarations and class members. A chain of |
| 25 | * folders that each hold only one folder shows as one block, so deep paths stay one step away. |
| 26 | */ |
| 27 | export class CodeModel { |
| 28 | readonly graph: CodeGraph; |
| 29 | readonly #children = new Map<NodeId, NodeId[]>(); |
| 30 | readonly #parents = new Map<NodeId, NodeId>(); |
| 31 | readonly #symbols = new Map<string, CodeSymbol>(); |
| 32 | readonly #lines = new Map<string, number>(); |
| 33 | readonly #outgoing = new Map<string, CodeEdge[]>(); |
| 34 | readonly #incoming = new Map<string, CodeEdge[]>(); |
| 35 | readonly #changes = new Map<string, CodeChange>(); |
| 36 | readonly #added = new Map<string, Set<number>>(); |
| 37 | readonly #diffs = new Map<NodeId, LineDiff>(); |
| 38 | readonly #reaching = new Set<string>(); |
| 39 | readonly #chains = new Map<NodeId, readonly NodeId[]>(); |
| 40 | readonly changedSymbols: readonly string[]; |
| 41 | |
| 42 | constructor(graph: CodeGraph, changes: readonly CodeChange[] = []) { |
| 43 | this.graph = graph; |
| 44 | for (const symbol of graph.symbols) this.#symbols.set(symbol.id, symbol); |
| 45 | for (const file of graph.files) this.#lines.set(file.path, file.lines); |
| 46 | for (const edge of graph.edges) { |
| 47 | push(this.#outgoing, edge.from, edge); |
| 48 | push(this.#incoming, edge.to, edge); |
| 49 | } |
| 50 | this.#buildTree(); |
| 51 | for (const change of changes) this.#changes.set(change.path, change); |
| 52 | for (const change of changes) this.#added.set(change.path, new Set(change.added)); |
| 53 | this.changedSymbols = this.#mapChanges(); |
| 54 | this.#findReaching(); |
| 55 | } |
| 56 | |
| 57 | get hasChanges(): boolean { |
| 58 | return this.#changes.size > 0; |
| 59 | } |
| 60 | |
| 61 | kids(id: NodeId): readonly NodeId[] { |
| 62 | return this.#children.get(id) ?? []; |
| 63 | } |
| 64 | |
| 65 | parent(id: NodeId): NodeId | null { |
| 66 | return this.#parents.get(id) ?? null; |
| 67 | } |
| 68 | |
| 69 | /** The blocks from the root down to this one. */ |
| 70 | chain(id: NodeId): readonly NodeId[] { |
| 71 | const known = this.#chains.get(id); |
| 72 | if (known) return known; |
| 73 | const parent = this.parent(id); |
| 74 | const chain = parent ? [...this.chain(parent), id] : [id]; |
| 75 | this.#chains.set(id, chain); |
| 76 | return chain; |
| 77 | } |
| 78 | |
| 79 | symbol(id: NodeId): CodeSymbol | undefined { |
| 80 | return this.#symbols.get(id); |
| 81 | } |
| 82 | |
| 83 | kind(id: NodeId): NodeKind { |
| 84 | if (id === ROOT) return "project"; |
| 85 | if (id.startsWith("dir:")) return "folder"; |
| 86 | if (id.startsWith("file:")) return "file"; |
| 87 | return this.#symbols.get(id)?.kind ?? "const"; |
| 88 | } |
| 89 | |
| 90 | label(id: NodeId): string { |
| 91 | if (id === ROOT) return "Project"; |
| 92 | const symbol = this.#symbols.get(id); |
| 93 | if (symbol) return symbol.name; |
| 94 | const path = id.slice(id.indexOf(":") + 1); |
| 95 | const parent = this.parent(id); |
| 96 | const base = parent && parent !== ROOT ? parent.slice(parent.indexOf(":") + 1) : ""; |
| 97 | const own = base && path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path; |
| 98 | return id.startsWith("dir:") ? `${own}/` : own; |
| 99 | } |
| 100 | |
| 101 | /** `Class.member` for a member, the name otherwise. */ |
| 102 | qualifiedName(id: NodeId): string { |
| 103 | const symbol = this.#symbols.get(id); |
| 104 | if (!symbol) return id.startsWith("file:") ? (id.split("/").pop() ?? id) : this.label(id); |
| 105 | const parent = symbol.parent ? this.#symbols.get(symbol.parent) : undefined; |
| 106 | return parent ? `${parent.name}.${symbol.name}` : symbol.name; |
| 107 | } |
| 108 | |
| 109 | /** Where a card's code comes from: a declaration's lines, or a whole file. Null for a folder. */ |
| 110 | span(id: NodeId): { readonly file: string; readonly start: number; readonly end: number } | null { |
| 111 | const symbol = this.#symbols.get(id); |
| 112 | if (symbol) return symbol; |
| 113 | if (id.startsWith("file:")) return { file: id.slice(5), start: 1, end: this.fileLines(id.slice(5)) }; |
| 114 | return null; |
| 115 | } |
| 116 | |
| 117 | /** A block and every block inside it. */ |
| 118 | within(id: NodeId): Set<NodeId> { |
| 119 | const inside = new Set([id]); |
| 120 | for (const node of inside) for (const kid of this.kids(node)) inside.add(kid); |
| 121 | return inside; |
| 122 | } |
| 123 | |
| 124 | fileLines(path: string): number { |
| 125 | return this.#lines.get(path) ?? 0; |
| 126 | } |
| 127 | |
| 128 | outgoing(id: string): readonly CodeEdge[] { |
| 129 | return this.#outgoing.get(id) ?? []; |
| 130 | } |
| 131 | |
| 132 | /** The declarations outside a block that use it, most uses first. */ |
| 133 | callers(id: string): string[] { |
| 134 | const inside = this.within(id); |
| 135 | const counts = new Map<string, number>(); |
| 136 | for (const target of inside) for (const edge of this.#incoming.get(target) ?? []) if (!inside.has(edge.from)) counts.set(edge.from, (counts.get(edge.from) ?? 0) + edge.count); |
| 137 | return [...counts].sort((a, b) => b[1] - a[1]).map(([from]) => from); |
| 138 | } |
| 139 | |
| 140 | /** The names a card of this block can follow, and where each one goes. Uses inside its members, or inside a whole file, count too. */ |
| 141 | followable(id: string): ReadonlyMap<string, string> { |
| 142 | const inside = this.within(id); |
| 143 | const names = new Map<string, string>(); |
| 144 | for (const from of inside) { |
| 145 | for (const edge of this.outgoing(from)) { |
| 146 | const target = this.#symbols.get(edge.to); |
| 147 | if (target && !inside.has(edge.to)) names.set(target.name, edge.to); |
| 148 | } |
| 149 | } |
| 150 | return names; |
| 151 | } |
| 152 | |
| 153 | /** Every declaration whose name contains `query`, best matches first. */ |
| 154 | search(query: string, limit: number): CodeSymbol[] { |
| 155 | const needle = query.trim().toLowerCase(); |
| 156 | if (!needle) return []; |
| 157 | return this.graph.symbols |
| 158 | .filter((symbol) => symbol.name.toLowerCase().includes(needle)) |
| 159 | .sort((a, b) => a.name.toLowerCase().indexOf(needle) - b.name.toLowerCase().indexOf(needle) || a.name.length - b.name.length) |
| 160 | .slice(0, limit); |
| 161 | } |
| 162 | |
| 163 | /** The declaration that a session most likely starts from: an exported function that nothing uses and that uses the most. */ |
| 164 | entryPoint(): string | null { |
| 165 | const used = new Set(this.graph.edges.map((edge) => edge.to)); |
| 166 | let best: string | null = null; |
| 167 | let reach = -1; |
| 168 | for (const symbol of this.graph.symbols) { |
| 169 | if (symbol.parent || symbol.kind !== "function" || !symbol.exported || used.has(symbol.id)) continue; |
| 170 | const out = this.outgoing(symbol.id).length; |
| 171 | if (out > reach) [best, reach] = [symbol.id, out]; |
| 172 | } |
| 173 | return best ?? this.graph.symbols[0]?.id ?? null; |
| 174 | } |
| 175 | |
| 176 | change(path: string): CodeChange | undefined { |
| 177 | return this.#changes.get(path); |
| 178 | } |
| 179 | |
| 180 | changes(): readonly CodeChange[] { |
| 181 | return [...this.#changes.values()]; |
| 182 | } |
| 183 | |
| 184 | /** Lines added and removed inside a block and everything in it. */ |
| 185 | diff(id: NodeId): LineDiff { |
| 186 | return this.#diffs.get(id) ?? NO_DIFF; |
| 187 | } |
| 188 | |
| 189 | status(id: NodeId): DiffStatus { |
| 190 | const diff = this.diff(id); |
| 191 | if (diff.added || diff.removed) { |
| 192 | const symbol = this.#symbols.get(id); |
| 193 | const added = symbol && this.#added.get(symbol.file); |
| 194 | if (symbol && added && !diff.removed && diff.added >= symbol.end - symbol.start + 1) return "added"; |
| 195 | return "changed"; |
| 196 | } |
| 197 | return this.#reaching.has(id) ? "reaches" : "none"; |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * The lines of a declaration for its card. With a change, removed lines sit where they were, and with `fold` |
| 202 | * the unchanged lines between changes fold into one row. |
| 203 | */ |
| 204 | cardLines(id: string, source: readonly string[] | null, fold: boolean): CardLine[] { |
| 205 | const symbol = this.span(id); |
| 206 | if (!symbol || !source) return []; |
| 207 | const change = this.#changes.get(symbol.file); |
| 208 | const added = this.#added.get(symbol.file); |
| 209 | const removedAfter = new Map<number, string[]>(); |
| 210 | for (const line of change?.removed ?? []) if (line.after >= symbol.start - 1 && line.after < symbol.end) push(removedAfter, line.after, line.text); |
| 211 | const lines: CardLine[] = [...(removedAfter.get(symbol.start - 1) ?? []).map((text) => ({ kind: "removed" as const, text }))]; |
| 212 | for (let number = symbol.start; number <= Math.min(symbol.end, source.length); number++) { |
| 213 | lines.push({ kind: "line", number, text: source[number - 1] ?? "", added: added?.has(number) ?? false }); |
| 214 | if (number < symbol.end) for (const text of removedAfter.get(number) ?? []) lines.push({ kind: "removed", text }); |
| 215 | } |
| 216 | if (!fold || !lines.some((line) => line.kind === "removed" || (line.kind === "line" && line.added))) return lines; |
| 217 | const keep = new Set<number>(); |
| 218 | lines.forEach((line, index) => { |
| 219 | if (line.kind === "removed" || (line.kind === "line" && line.added)) for (let near = index - FOLD_CONTEXT; near <= index + FOLD_CONTEXT; near++) keep.add(near); |
| 220 | }); |
| 221 | const folded: CardLine[] = []; |
| 222 | let skipped = 0; |
| 223 | lines.forEach((line, index) => { |
| 224 | if (!keep.has(index)) return void skipped++; |
| 225 | if (skipped) folded.push({ kind: "fold", count: skipped }); |
| 226 | skipped = 0; |
| 227 | folded.push(line); |
| 228 | }); |
| 229 | if (skipped) folded.push({ kind: "fold", count: skipped }); |
| 230 | return folded; |
| 231 | } |
| 232 | |
| 233 | #buildTree() { |
| 234 | const folders = new Map<string, { folders: Set<string>; files: string[] }>(); |
| 235 | const folder = (path: string) => folders.get(path) ?? folders.set(path, { folders: new Set(), files: [] }).get(path)!; |
| 236 | for (const file of this.graph.files) { |
| 237 | const parts = file.path.split("/"); |
| 238 | for (let depth = 0; depth < parts.length - 1; depth++) folder(parts.slice(0, depth).join("/")).folders.add(parts.slice(0, depth + 1).join("/")); |
| 239 | folder(parts.slice(0, -1).join("/")).files.push(file.path); |
| 240 | } |
| 241 | folder(""); |
| 242 | const collapse = (path: string): string => { |
| 243 | let at = path; |
| 244 | for (let entry = folders.get(at); entry && entry.files.length === 0 && entry.folders.size === 1; entry = folders.get(at)) at = [...entry.folders][0]; |
| 245 | return at; |
| 246 | }; |
| 247 | const visit = (node: NodeId, path: string) => { |
| 248 | const entry = folders.get(path)!; |
| 249 | const kids = [...[...entry.folders].sort().map((child) => `dir:${collapse(child)}`), ...entry.files.sort().map((file) => `file:${file}`)]; |
| 250 | this.#children.set(node, kids); |
| 251 | for (const kid of kids) { |
| 252 | this.#parents.set(kid, node); |
| 253 | if (kid.startsWith("dir:")) visit(kid, kid.slice(4)); |
| 254 | } |
| 255 | }; |
| 256 | visit(ROOT, collapse("")); |
| 257 | const byFile = new Map<string, NodeId[]>(); |
| 258 | for (const symbol of this.graph.symbols) { |
| 259 | const holder = symbol.parent ?? `file:${symbol.file}`; |
| 260 | this.#parents.set(symbol.id, holder); |
| 261 | push(byFile, holder, symbol.id); |
| 262 | } |
| 263 | for (const [holder, ids] of byFile) this.#children.set(holder, ids.sort((a, b) => this.#symbols.get(a)!.start - this.#symbols.get(b)!.start)); |
| 264 | } |
| 265 | |
| 266 | /** Gives each changed line to the innermost declaration that holds it, and sums the counts up the tree. */ |
| 267 | #mapChanges(): string[] { |
| 268 | const touched = new Set<string>(); |
| 269 | const count = (id: NodeId, key: keyof LineDiff) => { |
| 270 | for (const at of this.chain(id)) { |
| 271 | const diff = this.#diffs.get(at) ?? NO_DIFF; |
| 272 | this.#diffs.set(at, { ...diff, [key]: diff[key] + 1 }); |
| 273 | } |
| 274 | }; |
| 275 | for (const change of this.#changes.values()) { |
| 276 | const file = `file:${change.path}`; |
| 277 | if (!this.#parents.has(file)) continue; |
| 278 | const owner = (line: number) => this.#innermost(change.path, line) ?? file; |
| 279 | for (const line of change.added) { |
| 280 | const id = owner(line); |
| 281 | count(id, "added"); |
| 282 | if (id !== file) touched.add(id); |
| 283 | } |
| 284 | for (const line of change.removed) { |
| 285 | const id = owner(Math.max(1, line.after)); |
| 286 | count(id, "removed"); |
| 287 | if (id !== file) touched.add(id); |
| 288 | } |
| 289 | } |
| 290 | return [...touched].sort((a, b) => { |
| 291 | const x = this.#symbols.get(a)!; |
| 292 | const y = this.#symbols.get(b)!; |
| 293 | return x.file.localeCompare(y.file) || x.start - y.start; |
| 294 | }); |
| 295 | } |
| 296 | |
| 297 | #innermost(path: string, line: number): string | null { |
| 298 | let best: CodeSymbol | null = null; |
| 299 | for (const id of this.kids(`file:${path}`)) { |
| 300 | const symbol = this.#symbols.get(id)!; |
| 301 | if (line < symbol.start || line > symbol.end) continue; |
| 302 | best = symbol; |
| 303 | for (const member of this.kids(id)) { |
| 304 | const inner = this.#symbols.get(member)!; |
| 305 | if (line >= inner.start && line <= inner.end) best = inner; |
| 306 | } |
| 307 | } |
| 308 | return best?.id ?? null; |
| 309 | } |
| 310 | |
| 311 | /** Declarations that use a changed one, directly or through others. A type use counts only one step away. */ |
| 312 | #findReaching() { |
| 313 | const queue: [string, number][] = this.changedSymbols.map((id) => [id, 0]); |
| 314 | const seen = new Set(this.changedSymbols); |
| 315 | for (let index = 0; index < queue.length; index++) { |
| 316 | const [id, depth] = queue[index]; |
| 317 | for (const edge of this.#incoming.get(id) ?? []) { |
| 318 | if ((edge.kind === "types" && depth > 0) || seen.has(edge.from)) continue; |
| 319 | seen.add(edge.from); |
| 320 | this.#reaching.add(edge.from); |
| 321 | queue.push([edge.from, depth + 1]); |
| 322 | } |
| 323 | } |
| 324 | for (const id of [...this.#reaching]) for (const at of this.chain(id)) this.#reaching.add(at); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | function push<K, V>(map: Map<K, V[]>, key: K, value: V) { |
| 329 | const list = map.get(key); |
| 330 | if (list) list.push(value); |
| 331 | else map.set(key, [value]); |
| 332 | } |