forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueries.ts
More file actions
428 lines (373 loc) · 11.5 KB
/
queries.ts
File metadata and controls
428 lines (373 loc) · 11.5 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Graph Query Functions
*
* Higher-level query functions built on top of traversal algorithms.
*/
import { Node, Edge, Context, Subgraph, EdgeKind } from '../types';
import { QueryBuilder } from '../db/queries';
import { GraphTraverser } from './traversal';
/**
* Graph query manager for complex queries
*/
export class GraphQueryManager {
private queries: QueryBuilder;
private traverser: GraphTraverser;
constructor(queries: QueryBuilder) {
this.queries = queries;
this.traverser = new GraphTraverser(queries);
}
/**
* Get full context for a node
*
* Returns the focal node along with its ancestors, children,
* and both incoming and outgoing references.
*
* @param nodeId - ID of the focal node
* @returns Context object with all related information
*/
getContext(nodeId: string): Context {
const focal = this.queries.getNodeById(nodeId);
if (!focal) {
throw new Error(`Node not found: ${nodeId}`);
}
// Get ancestors (containment hierarchy)
const ancestors = this.traverser.getAncestors(nodeId);
// Get children
const children = this.traverser.getChildren(nodeId);
// Get incoming references (things that reference this node)
const incomingEdges = this.queries.getIncomingEdges(nodeId);
const incomingRefs: Array<{ node: Node; edge: Edge }> = [];
for (const edge of incomingEdges) {
// Skip containment edges (already in ancestors)
if (edge.kind === 'contains') {
continue;
}
const node = this.queries.getNodeById(edge.source);
if (node) {
incomingRefs.push({ node, edge });
}
}
// Get outgoing references (things this node references)
const outgoingEdges = this.queries.getOutgoingEdges(nodeId);
const outgoingRefs: Array<{ node: Node; edge: Edge }> = [];
for (const edge of outgoingEdges) {
// Skip containment edges (already in children)
if (edge.kind === 'contains') {
continue;
}
const node = this.queries.getNodeById(edge.target);
if (node) {
outgoingRefs.push({ node, edge });
}
}
// Get type information (type_of, returns edges)
const types: Node[] = [];
const typeEdgeKinds: EdgeKind[] = ['type_of', 'returns'];
for (const kind of typeEdgeKinds) {
const typeEdges = this.queries.getOutgoingEdges(nodeId, [kind]);
for (const edge of typeEdges) {
const typeNode = this.queries.getNodeById(edge.target);
if (typeNode && !types.some((t) => t.id === typeNode.id)) {
types.push(typeNode);
}
}
}
// Get relevant imports
const imports: Node[] = [];
const fileNode = ancestors.find((a) => a.kind === 'file');
if (fileNode) {
const importEdges = this.queries.getOutgoingEdges(fileNode.id, ['imports']);
for (const edge of importEdges) {
const importNode = this.queries.getNodeById(edge.target);
if (importNode) {
imports.push(importNode);
}
}
}
return {
focal,
ancestors,
children,
incomingRefs,
outgoingRefs,
types,
imports,
};
}
/**
* Get dependencies of a file
*
* Returns all files that this file imports from.
*
* @param filePath - Path to the file
* @returns Array of file paths this file depends on
*/
getFileDependencies(filePath: string): string[] {
const nodes = this.queries.getNodesByFile(filePath);
const fileNode = nodes.find((n) => n.kind === 'file');
if (!fileNode) {
return [];
}
const dependencies = new Set<string>();
const importEdges = this.queries.getOutgoingEdges(fileNode.id, ['imports']);
for (const edge of importEdges) {
const targetNode = this.queries.getNodeById(edge.target);
if (targetNode && targetNode.filePath !== filePath) {
dependencies.add(targetNode.filePath);
}
}
return Array.from(dependencies);
}
/**
* Get dependents of a file
*
* Returns all files that import from this file.
*
* @param filePath - Path to the file
* @returns Array of file paths that depend on this file
*/
getFileDependents(filePath: string): string[] {
const nodes = this.queries.getNodesByFile(filePath);
const dependents = new Set<string>();
// Check file-level incoming import edges (file:X imports file:Y)
const fileNode = nodes.find((n) => n.kind === 'file');
if (fileNode) {
const incomingFileEdges = this.queries.getIncomingEdges(fileNode.id, ['imports']);
for (const edge of incomingFileEdges) {
const sourceNode = this.queries.getNodeById(edge.source);
if (sourceNode && sourceNode.filePath !== filePath) {
dependents.add(sourceNode.filePath);
}
}
}
// Also check node-level imports of exported symbols
for (const node of nodes) {
if (node.isExported) {
const incomingEdges = this.queries.getIncomingEdges(node.id, ['imports']);
for (const edge of incomingEdges) {
const sourceNode = this.queries.getNodeById(edge.source);
if (sourceNode && sourceNode.filePath !== filePath) {
dependents.add(sourceNode.filePath);
}
}
}
}
return Array.from(dependents);
}
/**
* Get all symbols exported by a file
*
* @param filePath - Path to the file
* @returns Array of exported nodes
*/
getExportedSymbols(filePath: string): Node[] {
const nodes = this.queries.getNodesByFile(filePath);
return nodes.filter((n) => n.isExported);
}
/**
* Find symbols by qualified name pattern
*
* @param pattern - Pattern to match (supports * wildcard)
* @returns Array of matching nodes
*/
findByQualifiedName(pattern: string): Node[] {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.');
const regex = new RegExp(`^${regexPattern}$`);
// This is inefficient for large graphs - would need FTS index on qualified_name
// For now, use kind-based filtering if possible
const allNodes: Node[] = [];
const kinds: Node['kind'][] = [
'class',
'function',
'method',
'interface',
'type_alias',
'variable',
'constant',
];
for (const kind of kinds) {
const nodes = this.queries.getNodesByKind(kind);
for (const node of nodes) {
if (regex.test(node.qualifiedName)) {
allNodes.push(node);
}
}
}
return allNodes;
}
/**
* Get the module/package structure
*
* Returns a tree structure of files organized by directory.
*
* @returns Map of directory paths to contained files
*/
getModuleStructure(): Map<string, string[]> {
const files = this.queries.getAllFiles();
const structure = new Map<string, string[]>();
for (const file of files) {
const parts = file.path.split('/');
const dir = parts.slice(0, -1).join('/') || '.';
if (!structure.has(dir)) {
structure.set(dir, []);
}
structure.get(dir)!.push(file.path);
}
return structure;
}
/**
* Find circular dependencies in the graph
*
* @returns Array of cycles, each cycle is an array of node IDs
*/
findCircularDependencies(): string[][] {
const files = this.queries.getAllFiles();
const cycles: string[][] = [];
const visited = new Set<string>();
const recursionStack = new Set<string>();
const dfs = (filePath: string, path: string[]): void => {
if (recursionStack.has(filePath)) {
// Found a cycle
const cycleStart = path.indexOf(filePath);
if (cycleStart !== -1) {
cycles.push(path.slice(cycleStart));
}
return;
}
if (visited.has(filePath)) {
return;
}
visited.add(filePath);
recursionStack.add(filePath);
const dependencies = this.getFileDependencies(filePath);
for (const dep of dependencies) {
dfs(dep, [...path, filePath]);
}
recursionStack.delete(filePath);
};
for (const file of files) {
if (!visited.has(file.path)) {
dfs(file.path, []);
}
}
return cycles;
}
/**
* Get complexity metrics for a node
*
* @param nodeId - ID of the node
* @returns Object containing various complexity metrics
*/
getNodeMetrics(nodeId: string): {
incomingEdgeCount: number;
outgoingEdgeCount: number;
callCount: number;
callerCount: number;
childCount: number;
depth: number;
} {
const incomingEdges = this.queries.getIncomingEdges(nodeId);
const outgoingEdges = this.queries.getOutgoingEdges(nodeId);
const callEdges = outgoingEdges.filter((e) => e.kind === 'calls');
const callerEdges = incomingEdges.filter((e) => e.kind === 'calls');
const containsEdges = outgoingEdges.filter((e) => e.kind === 'contains');
const ancestors = this.traverser.getAncestors(nodeId);
return {
incomingEdgeCount: incomingEdges.length,
outgoingEdgeCount: outgoingEdges.length,
callCount: callEdges.length,
callerCount: callerEdges.length,
childCount: containsEdges.length,
depth: ancestors.length,
};
}
/**
* Find dead code (nodes with no incoming references)
*
* @param kinds - Node kinds to check (default: functions, methods, classes)
* @returns Array of unreferenced nodes
*/
findDeadCode(kinds?: Node['kind'][]): Node[] {
const targetKinds = kinds || ['function', 'method', 'class'];
const deadCode: Node[] = [];
for (const kind of targetKinds) {
const nodes = this.queries.getNodesByKind(kind);
for (const node of nodes) {
// Skip exported symbols (they may be used externally)
if (node.isExported) {
continue;
}
const incomingEdges = this.queries.getIncomingEdges(node.id);
// Filter out containment edges
const references = incomingEdges.filter((e) => e.kind !== 'contains');
if (references.length === 0) {
deadCode.push(node);
}
}
}
return deadCode;
}
/**
* Get subgraph containing nodes matching a filter
*
* @param filter - Filter function to select nodes
* @param includeEdges - Whether to include edges between matching nodes
* @returns Subgraph containing matching nodes
*/
getFilteredSubgraph(
filter: (node: Node) => boolean,
includeEdges: boolean = true
): Subgraph {
const nodes = new Map<string, Node>();
const edges: Edge[] = [];
// Get all nodes of common kinds
const kinds: Node['kind'][] = [
'file',
'module',
'class',
'struct',
'interface',
'trait',
'function',
'method',
'variable',
'constant',
'enum',
'type_alias',
];
for (const kind of kinds) {
const kindNodes = this.queries.getNodesByKind(kind);
for (const node of kindNodes) {
if (filter(node)) {
nodes.set(node.id, node);
}
}
}
// Include edges between matching nodes
if (includeEdges) {
for (const nodeId of nodes.keys()) {
const outgoing = this.queries.getOutgoingEdges(nodeId);
for (const edge of outgoing) {
if (nodes.has(edge.target)) {
edges.push(edge);
}
}
}
}
return {
nodes,
edges,
roots: [],
};
}
/**
* Access the underlying traverser for direct traversal operations
*/
getTraverser(): GraphTraverser {
return this.traverser;
}
}