forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrust.ts
More file actions
239 lines (208 loc) · 7.73 KB
/
rust.ts
File metadata and controls
239 lines (208 loc) · 7.73 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
/**
* Rust Framework Resolver
*
* Handles Actix-web, Rocket, Axum, and common Rust patterns.
*/
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { getCargoWorkspaceCrateMap } from './cargo-workspace';
const cargoWorkspaceMapCache = new WeakMap<ResolutionContext, Map<string, string>>();
function getCachedCargoWorkspaceCrateMap(context: ResolutionContext): Map<string, string> {
const cached = cargoWorkspaceMapCache.get(context);
if (cached) return cached;
const map = getCargoWorkspaceCrateMap(context);
cargoWorkspaceMapCache.set(context, map);
return map;
}
export const rustResolver: FrameworkResolver = {
name: 'rust',
languages: ['rust'],
detect(context: ResolutionContext): boolean {
// Check for Cargo.toml (Rust project signature)
return context.fileExists('Cargo.toml');
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// Pattern 1: Handler references
if (ref.referenceName.endsWith('_handler') || ref.referenceName.startsWith('handle_')) {
const result = resolveByNameAndKind(ref.referenceName, FUNCTION_KINDS, HANDLER_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
}
// Pattern 2: Service/Repository trait implementations
if (ref.referenceName.endsWith('Service') || ref.referenceName.endsWith('Repository')) {
const result = resolveByNameAndKind(ref.referenceName, SERVICE_KINDS, SERVICE_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
}
// Pattern 3: Struct references (PascalCase)
if (/^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
const result = resolveByNameAndKind(ref.referenceName, STRUCT_KINDS, MODEL_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.7,
resolvedBy: 'framework',
};
}
}
// Pattern 4: Module references
if (/^[a-z_]+$/.test(ref.referenceName)) {
const result = resolveModule(ref.referenceName, context);
if (result) {
// Workspace-manifest hits are an exact crate-name -> crate-root
// mapping straight from Cargo.toml, so we trust them above
// name-matcher self-file matches (which otherwise win at 0.7
// because every file containing `use foo::...` has its own
// import node named `foo`).
return {
original: ref,
targetNodeId: result.targetId,
confidence: result.fromWorkspace ? 0.95 : 0.6,
resolvedBy: 'framework',
};
}
}
return null;
},
extract(filePath, content) {
if (!filePath.endsWith('.rs')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'rust');
// Actix-web / Rocket attribute: #[get("/path")] fn handler(..)
// Capture the method, path, and the fn identifier that follows.
const attrRegex = /#\[(get|post|put|patch|delete|head|options)\s*\(\s*["']([^"']+)["'][^\]]*\)\]/g;
let match: RegExpExecArray | null;
while ((match = attrRegex.exec(safe)) !== null) {
const [, method, routePath] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'rust',
updatedAt: now,
};
nodes.push(routeNode);
const tail = safe.slice(match.index + match[0].length);
const fnMatch = tail.match(/\n\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);
if (fnMatch) {
references.push({
fromNodeId: routeNode.id,
referenceName: fnMatch[1]!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'rust',
});
}
}
// Axum: .route("/path", get(handler))
const axumRegex = /\.route\s*\(\s*"([^"]+)"\s*,\s*(get|post|put|patch|delete)\s*\(\s*(\w+)/g;
while ((match = axumRegex.exec(safe)) !== null) {
const [, routePath, method, handler] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'rust',
updatedAt: now,
};
nodes.push(routeNode);
references.push({
fromNodeId: routeNode.id,
referenceName: handler!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'rust',
});
}
return { nodes, references };
},
};
// Directory patterns
const HANDLER_DIRS = ['/handlers/', '/handler/', '/api/', '/routes/', '/controllers/'];
const SERVICE_DIRS = ['/services/', '/service/', '/repository/', '/domain/'];
const MODEL_DIRS = ['/models/', '/model/', '/entities/', '/entity/', '/domain/', '/types/'];
const FUNCTION_KINDS = new Set(['function']);
const SERVICE_KINDS = new Set(['struct', 'trait']);
const STRUCT_KINDS = new Set(['struct']);
/**
* Resolve a symbol by name using indexed queries instead of scanning all files.
*/
function resolveByNameAndKind(
name: string,
kinds: Set<string>,
preferredDirPatterns: string[],
context: ResolutionContext,
): string | null {
const candidates = context.getNodesByName(name);
if (candidates.length === 0) return null;
const kindFiltered = candidates.filter((n) => kinds.has(n.kind));
if (kindFiltered.length === 0) return null;
// Prefer candidates in framework-conventional directories
const preferred = kindFiltered.filter((n) =>
preferredDirPatterns.some((d) => n.filePath.includes(d))
);
if (preferred.length > 0) return preferred[0]!.id;
// Fall back to any match
return kindFiltered[0]!.id;
}
interface ModuleResolution {
targetId: string;
fromWorkspace: boolean;
}
function resolveModule(name: string, context: ResolutionContext): ModuleResolution | null {
// Rust modules can be either mod.rs in a directory or name.rs
const localPaths = [`src/${name}.rs`, `src/${name}/mod.rs`];
const workspaceCrates = getCachedCargoWorkspaceCrateMap(context);
const cratePath = workspaceCrates.get(name);
const workspacePaths = cratePath
? [`${cratePath}/src/lib.rs`, `${cratePath}/src/main.rs`]
: [];
const candidates: Array<{ path: string; fromWorkspace: boolean }> = [
...localPaths.map((path) => ({ path, fromWorkspace: false })),
...workspacePaths.map((path) => ({ path, fromWorkspace: true })),
];
for (const { path: modPath, fromWorkspace } of candidates) {
if (!context.fileExists(modPath)) continue;
const nodes = context.getNodesInFile(modPath);
const modNode = nodes.find((n) => n.kind === 'module');
if (modNode) return { targetId: modNode.id, fromWorkspace };
if (nodes.length > 0) return { targetId: nodes[0]!.id, fromWorkspace };
}
return null;
}